【发布时间】:2016-06-23 10:53:38
【问题描述】:
在我的 Android 应用中,我通过在我的MyActivity 中启动服务来安排任务:
@Override
protected void onResume() {
super.onResume();
synchronized (this) {
if (!serviceDidStart) {
serviceDidStart = true;
Intent intent = new Intent(this, CustomService.class);
startService(intent);
}
}
@Override
protected void onPause() {
super.onPause();
Intent intent = new Intent(this, CustomService.class);
stopService(intent);
serviceDidStart = false;
}
然后在我的CustomService:
private ScheduledExecutorService scheduler;
private scheduled = false;
private Runnable repeatingTask = new Runnable() {
@Override
public void run() {
System.out.println("Thread: " + Thread.currentThread().getId());
}
};
@Override
public void onCreate() {
scheduler = Executors.newSingleThreadScheduledExecutor();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!scheduled) {
scheduler.scheduleWithFixedDelay(repeatingTask, 0, 5, TimeUnit.SECONDS);
scheduled = true;
}
return Service.START_STICKY;
}
我希望该任务仅在一个线程中调度和执行,这应该会产生如下输出:
线程:350
线程:350
线程:350
如果我在发布后不做任何其他事情,它就可以正常工作。但是,如果我按下主页按钮,然后恢复我的应用程序,输出和任务调度就会变得一团糟,如下所示:
线程:350
线程:362
线程:367
线程:350
线程:362
线程:367
我做错了吗?如果我想在应用程序的整个生命周期内仅在一个线程中调度和执行 repeatingTask(即即使在我暂停并恢复到活动后也只使用一个线程来调度和执行任务),我应该怎么做?
我对 Android 和 Java 开发还很陌生,我不知道我的情况出了什么问题。任何帮助和指导都会很棒,谢谢!
更新和编辑:
- 在
MyActivity的onPause()中添加回serviceDidStart = false;
【问题讨论】:
-
如果它只能在应用程序生命周期内工作,为什么要使用服务?您可以在 Activity 中创建 ExecutorService。只需将其关闭 onPause 并创建一个新的(和计划) onResume ...
标签: java android multithreading android-service