綁定式服務
第一次綁定服務自動調用 onCreate->onBind 多次調用綁定服務 不會調用任何方法. 只能解綁一次,解綁時調用 unBind->onDestroy
當onBind返回值不爲null,函數的執行過程爲onCreate->onBind->ServiceConnection.onServiceConnected
如果Activity已經成功綁定過一個服務,ctivity報異常
Activity has leaked ServiceConnection that was originally bound here
解決:退出前先解綁
ServiceConnection serviceConnection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name,
IBinder service)
{
LHBindService.MyIBinder s=(LHBindService.MyIBinder)service;
System.out.println("MainActivity.onServiceConnected " +
"Random "+s.getRandom());
System.out.println("name = [" + name + "], service = ["
+ service + "]");
@Override
/**
* 當服務"異常"斷開時調用的方法
*/
public void onServiceDisconnected(ComponentName name)
{
System.out.println("MainActivity.onServiceDisconnected");
System.out.println("name = [" + name + "]");
};
Intent intent=new Intent(this,LHBindService.class);
intent.putExtra("key","傳值");
bindService(intent//意圖對象,指定要綁定的服務
,serviceConnection//服務連接對象
,BIND_AUTO_CREATE//標誌位,如果沒有創建服務則自動創建
);