onDestroy()回调服务

时间:2014-01-17 14:51:16

标签: android android-intent android-service

在我的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();
   }
}

根据我的日志,onDestroy()的{​​{1}}在MyService完成后执行。

我如何保证在doAnotherTask()被调用之前onDestory() MyService被执行?

P.S。:我以为我可以这样做:

doAnotherTask()

但是可能没有服务已经开始,这意味着boolean isStopped = context.stopService(new Intent(context, MyService.class)); if(isStopped){ doAnotherTask(); } 什么都不做。所以,我不能依赖上面的代码。

2 个答案:

答案 0 :(得分:0)

调用startActivityForResult()....并在获得onActivityResult之后,....调用你的方法doAnotherTask() 我认为这将完成这项工作

答案 1 :(得分:0)

如何从onDestroy()函数向广播接收器发送特殊意图?当你的接收者得到它,然后调用doAnotherTask()。 (我假设您不能直接从onDestroy()调用doAnotherTask()。)