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

Per*_*OMM 5 service android android-8.0-oreo 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>
Run Code Online (Sandbox Code Playgroud)

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Com*_*are 10

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

这个应用程序 ID 为 的示例应用程序中com.commonsware.android.r.embed.server,我有一个绑定服务。

此示例客户端应用程序中,我将这些行添加到清单中,以允许客户端应用程序绑定到服务应用程序:

  <queries>
    <package android:name="com.commonsware.android.r.embed.server" />
  </queries>
Run Code Online (Sandbox Code Playgroud)