android - 不会触发后续的 onBind() 调用

标签 android android-intent android-service

使用 gingerbread 2.3.4 api lvl 10。

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

问题是当它第一次绑定(bind)时,服务上的 onBind() 被触发。进一步的绑定(bind)不会调用服务上的 onBind()。我相信问题是服务直接在 after_boot 启动。当我不在启动时启动服务并让 Activity 使用 Context.BIND_AUTO_CREATE 启动它时,它确实按预期运行。

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

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

PS:我已经在 aidl 中实现了它,但我不喜欢它,因为该服务将执行一些异步操作以返回数据,我必须在两个应用程序中添加 aidl 文件,将添加导致代码臃肿的处理程序.

提前致谢。我的代码 fragment :

服务 list :

        <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>

当我绑定(bind)到服务时:

Intent intent = new Intent(WORK_INTENT); intent.putExtra("参数", 参数);

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

当我得到结果时:

context.unbindService(mConnection);
context.unregisterReceiver (broadcastReceiver);

最佳答案

来自关于绑定(bind)到服务的文档:

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 是完全可以的,尽管原始绑定(bind)仍然会发送到客户端,而不是你可能生成的任何新绑定(bind)您对 onBind 的新调用。 (即,你真的不应该调用 onBind,而只是将 onRebind 作为一个单独的案例来处理)

关于android - 不会触发后续的 onBind() 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11191693/

相关文章:

android - 仅允许选定的应用程序在 Android 中进行旁加载

java - 将 HttpClient 响应转换为 JsonObject 时出错

c# - 为什么 Intent.ActionView 对 MP4 文件抛出错误

android - 调用另一个应用程序的 Activity 时出现 ActivityNotFoundException

Android:当服务被杀死时,我们如何保持服务状态以供以后恢复?

android - 如何调整ListView中的ImageView?

android - 如何在 map fragment API v2 布局顶部添加按钮

android - 如何使用 Intent 在图库应用程序中打开相册

java - 使用 Android 前台服务为 MediaPlayer 创建通知

android - 如何使用startForeground?