问题描述
<service
android:name="com.example.app.service.MyService"
android:exported="true">
<intent-filter>
<action android:name="com.example.app.START_MY_SERVICE" />
</intent-filter>
</service>
另一个应用程序使用(3 种可能的方法)启动第一个应用程序的服务:
1:
val i = Intent("com.example.app.START_MY_SERVICE").apply {
setPackage("com.example.app")
}
startService(i)
2:
val i = Intent().apply {
component = ComponentName("com.example.app","com.example.app.service.MyService")
}
startService(i)
3:
val i = Intent().apply {
setClassName("com.example.app","com.example.app.service.MyService")
}
startService(i)
从 23 API (6 Android) 到 29 API (10 Android),所有这些启动另一个应用程序服务的方法都适用
在 Android 11 (30 API) 上它不起作用,服务没有启动,也不例外:
使用 2-3 种方法时,在 Logcat 中打印:
W/ActivityManager: Unable to start service Intent { cmp=com.example.app.service/.service.MyService } U=0: not found
对于 1 个方法没有任何反应,Logcat 没有消息
那么我们如何在 Android 11 上从另一个应用启动某个应用的服务?
解决方法
启动另一个应用程序服务的应用程序必须在清单中包含下一个声明:
<queries>
<package android:name="com.example.anotherapp" />
</queries>
或
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
(Automate 和 Tasker 等应用拥有此权限)
感谢 CommonsWare Android 11: starting a service of another app