【发布时间】:2014-02-06 22:50:23
【问题描述】:
在我的Android项目中,我有一个普通的Service:
public class MyService extends Service{
@Override
public int onStartCommand(...){...}
...
@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyApp","MyService onDestroy() is called!");
}
}
在我的BroadcastReceiver 课程中,我停止MyService 并执行另一项任务:
public static class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.stopService(new Intent(context, MyService.class));
doAnotherTask();
}
}
根据我的日志,MyService中的onDestroy()是在doAnotherTask()完成后执行的。
如何保证MyService 的onDestory() 在doAnotherTask() 被调用之前执行?
P.S.:我想我可以做这样的事情:
boolean isStopped = context.stopService(new Intent(context, MyService.class));
if(isStopped){
doAnotherTask();
}
但可能没有服务已启动,这意味着stopService(...) 什么都不做。所以,我不能依赖我上面的代码。
【问题讨论】:
-
如果 onDestroy 已经在销毁它,那么为什么要手动停止它呢?或者如果你必须阻止它,那么为什么在 onDestroy() 里面?
-
@Saqib,恐怕你没有正确理解我的问题。我只调用 stopService() 之后我才执行另一个任务 (),就是这样。系统调用 onDestroy() 我没有,我只是 stopService() 。但我在 onDestroy() 回调中有一些东西。
-
你尝试过在两个任务之间稍微延迟一下吗?
-
不,这不是我想要的方式。
-
尝试在一个方法中停止你的服务,然后调用你的 anotherTask 方法,看看是否有效果!
标签: android android-intent android-service