突然遇到个问题, 问题描述:
我按照顺序来绑定一个服务:start->bind 最后在退出activity的时候unbind一下, 现在我有这样的业务需求,就是当我再次进入该activity时需要再次bind, 我发现再调用bind方法并不能绑定服务(不知道google工程师为啥要设计成这样。)
写了一段测试代码验证一下:
Service:
package org.load.testservice; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class MyService extends Service { @Override public IBinder onBind(Intent intent) { System.out.println("bind...."); return null; } @Override public void onCreate() { System.out.println("oncreate...."); super.onCreate(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { System.out.println("onstart...."); return super.onStartCommand(intent, flags, startId); } @Override public boolean onUnbind(Intent intent) { System.out.println("unbind...."); return super.onUnbind(intent); } @Override public void onDestroy() { System.out.println("destroy..."); super.onDestroy(); } }
activity:
package org.load.testservice; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.View; public class MainActivity extends Activity { private MyConn conn = new MyConn(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startService(View view) { startService(new Intent(this, MyService.class)); } public void bindService(View view) { bindService(new Intent(this, MyService.class), conn, Context.BIND_AUTO_CREATE); } public void unbindService(View view) { unbindService(conn); } private class MyConn implements ServiceConnection { @Override public void onServiceConnected(ComponentName name, IBinder service) { } @Override public void onServiceDisconnected(ComponentName name) { } } }
第一次按照顺序点击按钮发现没多大问题, 服务依次进行了create、start、bind、unbind。
但是当我再次点击“绑定服务”的时候问题出现了onBind方法没有执行!!也就是说没有成功绑定!!!
查看文档看到Service还有一个生命周期方法onRebind,好像看到希望了, 添加上再试试:
@Override public void onRebind(Intent intent) { System.out.println("rebind..."); super.onRebind(intent); }
怀着激动心情再次测试,logcat遗憾的告诉我还是不行!!!!
仔细查看onRebind的官方说明:
Called when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind
.
This will only be called if the implementation of onUnbind
was overridden to return true.
最重要的是最后一句话,意思是:这个方法只有当onUnbind返回true的时候才能被调用。
现在改写onUnbind:
@Override public boolean onUnbind(Intent intent) { System.out.println("unbind...."); return true; }
再次查看logcat, 别的不多说了,上图:
总结:
多次bind、unbind一个服务,只有在第一次的时候才会调用服务的onBind方法, 解除绑定后继续绑定并不会调用onBind而是调用了onRebind, 但是要想让onRebind顺利的调用还有一个条件就是onUnbind必须返回true。