+-
android – 后续的onBind()调用不会被触发
使用姜饼2.3.4 api lvl 10.

我在启动完成后启动服务.为此,我添加了一个启动服务的广播接收器.我在启动器中使用相同的服务.我试图通过向Intent添加额外的参数来绑定服务.通过广播回复从服务中获取结果.

问题是当它第一次绑定时,会触发服务上的onBind().进一步的绑定不会调用服务上的onBind().我相信问题是服务直接在after_boot启动.当我没有在启动时启动服务并让活动使用Context.BIND_AUTO_CREATE启动它时,它的行为与预期一致.

我想出的唯一解决方案是更改服务的onUnbind()并在服务的onRebind()调用中发出onBind().我不喜欢这个解决方案,因为它可能会破坏以后的Android版本,导致onBind()方法被调用两次.

那么为什么后续绑定不会在启动完成后启动的服务上触发.欢迎任何其他优雅的解决方案.

PS:我已经在aidl中实现了它,但我不喜欢它,因为服务将做一些异步的东西来返回数据,我必须在两个应用程序中添加aidl文件,将添加导致膨胀代码的处理程序.

提前致谢.我的代码片段:

服务的清单:
     

        <intent-filter>
            <action android:name="com.organization.android.ACTION_BOOT_COMPLETED" />
        </intent-filter>

         <intent-filter>
            <action android:name="com.organization.android.WORK_INTENT" />
        </intent-filter>
    </service>

    <receiver android:name=".CoreServiceReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" >
            </action>

            <category android:name="android.intent.category.HOME" >
            </category>
        </intent-filter>
    </receiver>

当我绑定到服务时:

Intent intent = new Intent(WORK_INTENT);
    intent.putExtra(“param”,param);

context.registerReceiver (broadcastReceiver, new IntentFilter("com.organization.android.WORK_RESULT"));
context.bindService(intent,mConnection, Context.BIND_AUTO_CREATE);        

}

当我得到结果时:

context.unbindService(mConnection);
context.unregisterReceiver (broadcastReceiver);
最佳答案
从绑定到服务的文档:

Multiple clients can connect to the service at once. However, the
system calls your service’s onBind() method to retrieve the IBinder
only when the first client binds. The system then delivers the same
IBinder to any additional clients that bind, without calling onBind()
again.

这种行为不会改变,因此覆盖onUnbind的方法返回true,然后在onRebind期间调用onBind是完全正常的,尽管原始绑定仍将发送到客户端,而不是您在新调用中可能生成的任何新绑定到onBind. (也就是说,你真的不应该调用onBind,而只是将onRebind作为一个单独的案例来处理)

点击查看更多相关文章

转载注明原文:android – 后续的onBind()调用不会被触发 - 乐贴网