忽然遇到個問題, 問題描述:java
我按照順序來綁定一個服務:start->bind 最後在退出activity的時候unbind一下, 如今我有這樣的業務需求,就是當我再次進入該activity時須要再次bind, 我發現再調用bind方法並不能綁定服務(不知道google工程師爲啥要設計成這樣。)android
寫了一段測試代碼驗證一下:app
Service:
ide
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。this
可是當我再次點擊「綁定服務」的時候問題出現了onBind方法沒有執行!!也就是說沒有成功綁定!!!
google
查看文檔看到Service還有一個生命週期方法onRebind,好像看到但願了, 添加上再試試:spa
@Override public void onRebind(Intent intent) { System.out.println("rebind..."); super.onRebind(intent); }
懷着激動心情再次測試,logcat遺憾的告訴我仍是不行!!!!設計
仔細查看onRebind的官方說明:code
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。