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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值