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还为空了。

你可能感兴趣的:(android,开发)