微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

移至 Android 11 后无法绑定到服务

如何解决移至 Android 11 后无法绑定到服务

我有两个应用程序。一种不使用 Android 11 中引入的任何权限(相机、位置等)的前台服务。我有连接到我的服务的客户端应用程序。在 android 8 中,此连接有效,但是在 Android 11 环境中调用 context.BindService() 时始终返回 false。

这是服务清单:

<service
            android:name="com.mypackage.myService"
            android:enabled="true"
            android:exported="true"
            tools:ignore="ExportedService">
        </service>

这是我在客户端使用的连接函数

fun connect(context: Context): Boolean {
    Intent().also {
        it.component = ComponentName(
            context.getString(R.string.middleware_package),context.getString(R.string.middleware_service)
        )
        val bound = context.bindService(it,connection,Context.BIND_AUTO_CREATE)

        if (!bound) {
            Log.e(LOG_TAG,"Unable to connect to service. Is the service installed?")
        }
        return bound
    }
}

在 bindService() 的 android 文档中,它声明它将返回 false“如果系统找不到服务或者您的客户端没有绑定到它的权限。”由于我的服务不使用任何新的 android 11 权限,我假设它现在没有正确找到服务?这怎么可能?

解决方法

您需要将 <queries> 元素添加到客户端应用程序的清单中,以标识服务应用程序。

在应用 ID 为 com.commonsware.android.r.embed.serverthis sample app 中,我有一个绑定服务。

this sample client app 中,我将这些行添加到清单中以允许客户端应用程序绑定到服务应用程序:

  <queries>
    <package android:name="com.commonsware.android.r.embed.server" />
  </queries>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。