>我成功地使用了一个服务在前台执行了某个任务。现在,要在后台执行此操作,我将在 onDestroy()
中删除 handler.removeCallbacks
方法。
但这也会阻止我使用 stopService(intent)
停止服务。
我在官方文档中看到我可能应该使用 JobScheduler(因为我的目标是 API 28(。
这是我的代码的更精确指示:
public class MainActivity {
private Intent intent;
onCreate() {
if (intent == null) {
intent = new Intent(this, MyService.class);
}
}
startService(intent);
... // Then is some code to stop the service if needed with stopService(intent)
}
--------------------------------------------------------------
public class myService {
private Handler handler = null;
private static Runnable runnable = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
System.out.println("Running service times " + i);
i++;
handler.postDelayed(runnable, 1000);
}
};
handler.post(runnable);
}
@Override
public void onDestroy() {
handler.removeCallbacks(runnable);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
我希望它在后台运行(即使设备已锁定(,但仍然能够禁用该服务(或 JobScheduler?
你有什么建议?
您可以使用工作管理器
或作业调度程序
并且有很多选择,例如同步适配器, 绑定服务, 意图服务
您可以根据需要使用这些选项之一