我成功地使用的服务做在前台某项任务。现在,这样做的背景下,我会删除handler.removeCallbacks
的onDestroy()
方法。
但是,这也使我不能停止使用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?)。
你有什么建议?