Android 服务的onDestroy()回调
在我的Android项目中,我有一个正常的Android 服务的onDestroy()回调,android,android-intent,android-service,Android,Android Intent,Android Service,在我的Android项目中,我有一个正常的服务: public class MyService extends Service{ @Override public int onStartCommand(...){...} ... @Override public void onDestroy() { super.onDestroy(); Log.d("MyApp","MyService onDestroy() is called!"); } } 在我
服务
:
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
的ondestory()
在doAnotherTask()完成后执行
如何保证在调用doAnotherTask()
之前执行MyService
的onDestory()
附言:我想我可以做如下事情:
boolean isStopped = context.stopService(new Intent(context, MyService.class));
if(isStopped){
doAnotherTask();
}
但是有可能没有服务已经启动,这意味着stopService(…)
什么也不做。所以,我不能依赖我上面的代码。调用startActivityForResult()。。。。在你得到onActivityResult之后,。。。。调用您的方法doAnotherTask()
我想这就可以了从onDestroy()函数向广播接收器发送一个特殊意图怎么样?当您的接收者收到它时,调用doAnotherTask()。(我假设您不能直接从onDestroy()调用doAnotherTask())我不是在活动中停止服务,我是在BroadcastReceiver类中。我更新了我的帖子。如果onDestroy已经在销毁它,那么为什么要手动停止呢?或者如果你必须停止,那么为什么在onDestroy()中?@Saqib,恐怕你没有正确理解我的问题。我只调用stopService(),然后再调用其他任务(),就是这样。系统调用onDestroy(),我没有,我只是停止了服务()。但是我在onDestroy()回调中遇到了一些问题。您是否尝试过在两个任务之间稍微延迟一点?不,这不是我想要的方式。请尝试在一个方法中停止您的服务,然后调用另一个任务方法,看看是否能做到这一点!这对我来说不是一个理想的解决方案,因为我的广播接收器用于接收系统广播的意图。此外,不可能在现有的广播接收器中注册另一个广播接收器。但您可以注册接收器以执行多个操作,然后检查onReceive()中的intent.getAction()以确定是执行正常处理还是执行清理任务。如果没有更多关于doAnotherTask()做什么的信息,我真的无法提供更好的想法。