bindService後,onServiceConnected方法沒有執行
在體驗bindService功能時候,執行過bindService後,也返回繫結成功,但是發現獲取Service的物件mBoundService一直為空,onServiceConnected沒有執行,一個晚上沒想明白,也嘗試了網上的一些做法,直到看到了下面的方法(http://www.itwendao.com/article/detail/286559.html),搞定。
即下面mBoundService引用的程式碼從onCreate挪到onServiceConnected裡去
mBoundService = (mMusicBinder).getService();
mBoundService.addMusicStateChangedListener (MainActivity.this);
mBoundService.setPath(DatabaseModel.getDatabaseModelInstance(MainActivity.this)
.getMusicItemById(1).getPath());
mBoundService.setPlayingId(1);
官網對於bindService有句描述:
Connect to an application service, creating it if needed. This defines a dependency between your application and the service. The given conn will receive the service object when it is created and be told if it dies and restarts. The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed.
大意是,onServiceConnected在繫結成功時進行回撥,但不保證在執行bindService後立馬回撥,我們在onCreate方法中繫結後立馬獲取service例項,但此時不保證onServiceConnected已經被回撥。 也就是我們onCreate方法執行時onServiceConnected還沒有別呼叫。此時當然mBoundService還為空了。