毁灭与摧毁在我的情况下重新创建服务

时间:2014-01-30 15:53:18

标签: android android-intent broadcastreceiver android-service android-broadcast

在我的活动中,我在我的活动的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文档所说,我的上述代码并不保证以前启动的服务将被销毁,因为我也绑定了它。

我的问题是,从MyService取消绑定 MyBroadcastReceiver从头开始重新启动MyService的最有效方法是什么?如您所见,绑定的myConnection实例位于MyActivity ...

1 个答案:

答案 0 :(得分:0)

来自Service文档:

  

多个客户端可以立即连接到该服务。然而   系统调用您的服务的onBind()方法来检索IBinder   只有当第一个客户绑定时。然后系统提供相同的功能   IBinder到绑定的任何其他客户端,而不调用onBind()   试。

     

当最后一个客户端从服务解除绑定时,系统会破坏该服务   service(除非服务也是由startService()启动的)。

因此,在使用您的服务时,请勿使用startService(intent)启动服务,而应使用bindService(service, conn, flags)启动服务。这样,如果您的Activity是绑定到该服务的唯一活动,当您致电unbindService(ServiceConnection conn)时系统将终止您的服务,那么您可以在之后重新绑定。

相关问题