bindService的注意事項

private ServiceConnection conn = new ServiceConnection()

{

@Override

public void onServiceDisconnected(ComponentName name)

{

// TODO Auto-generated method stub

}


@Override

public void onServiceConnected(ComponentName name, IBinder service)

{

binder = (MyBinder) service;

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

Fragment fragment = new PlayIndex(binder.cur,binder.list);

ft.replace(R.id.play, fragment);

ft.commit();

}

};


@Override

protected void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.play);


Intent intent = new Intent(Play.this, PlayService.class);

bindService(intent, conn, Context.BIND_AUTO_CREATE);




}


bindService的調用是異步的,也就是說到service的鏈接不是在bindService被調用後就馬上完成的。不瞭解這一點會導致一些問題,例如:雖然在bindService.onServiceConnected中有對binder的賦值,但如果以爲在onCreate中的bindService之後onServiceConnected就已經被調用了,就會出現問題,因爲其實這時binder仍然是null,到service的鏈接會在之後的某個時間點被建立,建立鏈接後系統會調用onServiceConnected這個函數,所以可以在這個函數中放置一些代碼來提醒當前activity到service的鏈接已經建立完畢。但具體最晚到什麼時候還不知道,猜測應該是onCreate執行完畢後吧。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章