问题描述
我有两个应用程序。一种不使用 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.server
的 this sample app 中,我有一个绑定服务。
在 this sample client app 中,我将这些行添加到清单中以允许客户端应用程序绑定到服务应用程序:
<queries>
<package android:name="com.commonsware.android.r.embed.server" />
</queries>