第一个应用程序有一个服务:
<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上我们如何从另一个应用程序启动某个应用程序的服务呢?