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

Unable to bind to service after moving to Android 11

我有两个应用程序。一个是前台服务,不使用 Android 11 中引入的任何权限(相机、位置等)。我有连接到我的服务的客户端应用程序。在 android 8 中此连接有效,但是在 Android 11 环境中调用 context.BindService() 总是 return 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 文档中声明它将 return false “如果系统找不到该服务或者如果您的客户端没有权限绑定到它”由于我的服务不使用任何新的 android 11 权限,我假设它现在没有正确找到服务?怎么会这样?

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

this sample app 中,应用程序 ID 为 com.commonsware.android.r.embed.server,我有一个绑定服务。

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

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