如何使处理程序始终 运行 尽管应用程序在 java 中关闭

how to make Handler always run although application closed in java

我想制作一个应用程序,可以在执行某些方法时按时间自动更新。我使用 Handler 让它按时间自动更新。时间到了,它会将数据更新到 firebase。它可以在应用程序未关闭时工作。但是当我在指定的更新时间之前关闭应用程序时,处理程序不起作用。尽管我使用了可以保留应用程序的服务 运行.

到目前为止这是我的代码:

AutoUpdate.java

public class AutoUpdate extends AppCompatActivity {
    TextView textDateTime;
    TextView textcurrentDateTime;
    DatabaseReference mDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto_update);

        String currentDate = DateFormat.getDateTimeInstance().format(new Date());
        textcurrentDateTime.setText(currentDate);

        final Handler handler=new Handler();
        final Runnable updateTask=new Runnable() {
            @Override
            public void run() {
                updateCurrentTimeToFirebase();
                handler.postDelayed(this,7000);
                handler.removeCallbacks(this);
            }
        };

        handler.postDelayed(updateTask,7000);
        startService(new Intent(this, MyService.class));
    }

    public  void updateCurrentTimeToFirebase() {
        String currentDate = DateFormat.getDateTimeInstance().format(new Date());
        mDatabase = FirebaseDatabase.getInstance().getReference();
        String id = mDatabase.push().getKey();
        mDatabase.child("autoUpdate").child(id).child("updateTime").setValue(currentDate);
    }
}

Myservice.java

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }
}

我需要你的帮助.. 非常感谢..

您正在创建后台服务,但所有操作仍在前台进行 activity 仅

按如下方式更改您的代码

AutoUpdate.class

public class AutoUpdate extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auto_update);

        if (!isMyServiceRunning(MyService.class)) {
            Intent intent = new Intent(AutoUpdate.this, MyService.class));
            startService(intent);
        }
   }
   private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
}

MyService.class

public class MyService extends Service {
    TextView textDateTime;
    TextView textcurrentDateTime;
    DatabaseReference mDatabase;

    public MyService() {

    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onDestroy() {
        Log.d("destroy", "onDestroy");
    }

    @Override
    public void onStart(Intent intent, int startid) {
        //return super.onStartCommand(intent, flags, startId);
        String currentDate = DateFormat.getDateTimeInstance().format(new Date());
        mDatabase = FirebaseDatabase.getInstance().getReference();
        textcurrentDateTime.setText(currentDate);

        final Handler handler=new Handler();
        final Runnable updateTask=new Runnable() {
            @Override
            public void run() {
                updateCurrentTimeToFirebase();
                handler.postDelayed(this,7000);
                handler.removeCallbacks(this);
            }
        };

        handler.postDelayed(updateTask,7000);
    }
    public  void updateCurrentTimeToFirebase() {
        String currentDate = DateFormat.getDateTimeInstance().format(new Date());
        String id = mDatabase.push().getKey();
        mDatabase.child("autoUpdate").child(id).child("updateTime").setValue(currentDate);
    }
}