【发布时间】:2014-01-30 15:53:18
【问题描述】:
在我的活动中,我在我的活动的onStart() 中启动我的服务并在onResume() 中绑定到服务:
public class MyActivity extends Activity{
private boolean isBound;
ServiceConnection myConnection = new ServiceConnection(){...};
@Override
public void onStart(){
super.onStart();
startService(new Intent(this, MyService.class));
}
@Override
public void onResume(){
super.onResume();
Intent service = new Intent(this, MyService.class);
isBound = bindService(service, myConnection, Context.BIND_AUTO_CREATE);
}
}
我有一个 BroadcastReceiver 类,在其 onReceive() 回调中,我想重新启动我的服务。我的意思是通过再次调用startService() 完全销毁它并创建它:
public class MyBroadcastReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//I want to re-start MyService from scratch, i.e. destroy it & start it (create it) again
Intent service = new Intent(context, MyService.class);
stopService(service);
startService(service);
}
}
但是正如Android文档所说,我上面的代码并不能保证之前启动的服务会被销毁,因为我也绑定了它。
我的问题是,unbind MyService in MyBroadcastReceiver 以从头开始重新启动 MyService 的最有效方法是什么?如您所见,绑定的myConnection 实例在MyActivity...
【问题讨论】:
-
您需要从 scratcg 重新启动服务而不是仅仅使用生命周期方法来重置其状态的动机是什么?
-
我在 MyService 的 onCreate() 中有一些动作,它必须在那里。我想在 BroadcastReceiver 中调用 onReceive() 时触发 MyService 的 onCreate()。那就是在那个时候再次从头开始提供干净的服务。
-
你的架构听起来很做作。如果您的
Service中的onCreate()中有代码,并且您希望在触发接收器时执行这些代码,则将该代码移动到一个单独的方法中并让您的接收器调用startService(),并在传递的Intent中添加一个额外的告诉你的Service重新初始化自己。在onCreate()和onStartCommand()中,您可以调用“初始化”方法。
标签: android android-intent broadcastreceiver android-service android-broadcast