场景
A 应用启动后 将B的servic拉起
android11
A 应用包名com.hryt.myapplication111
B 应用包名com.hryt.myapplication222
步骤
A 的清单文件中
<queries>
<package android:name="com.hryt.myapplication222" />
<intent>
<action android:name="com.hryt.myapplication222.service" />
</intent>
</queries>
或者 添加清单文件权限
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
A的代码中
Intent intent = new Intent();
intent.setAction("com.hryt.myapplication222.service");
intent.setPackage("com.hryt.myapplication222");
startForegroundService(intent);
B的清单文件中
<service
android:name="com.hryt.myapplication222.TestService2"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.hryt.myapplication222.service" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
注意点
在Android8.0以后的版本中直接使用startService()启动服务会出错,
因为Android8.0不再允许后台service直接通过startService的方式启动,该方法会引发IllegalStateException错误
相应的,写成这样 startForegroundService()
如何确保service不被杀死
1 变为前台服务(开一个通知栏通知)
2 onStartCommand
方式中,返回START_STICKY
3 变为系统自启动应用