【问题标题】:onDestroy() callback of Service服务的 onDestroy() 回调
【发布时间】: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()完成后执行的。

如何保证MyServiceonDestory()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


【解决方案1】:

调用 startActivityForResult() .... 在你得到 onActivityResult,.... 调用你的方法 doAnotherTask() 我认为这样就可以了

【讨论】:

  • 我没有在 Activity 中停止我的服务,我在 BroadcastReceiver 类中。我更新了我的帖子。
【解决方案2】:

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

【讨论】:

  • 这对我来说不是一个理想的解决方案,因为我的广播接收器用于接收系统广播的意图。此外,不可能在现有的广播接收器中注册另一个广播接收器。
  • 但是您可以为多个操作注册接收器,然后在 onReceive() 中检查 intent.getAction() 以确定是进行正常处理还是进行清理任务。如果没有更多关于 doAnotherTask() 作用的信息,我真的无法提供更好的想法。
猜你喜欢
  • 1970-01-01
  • 2011-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多