Android一個APP檢測另一個APP的Service被殺死時自動重啟服務
阿新 • • 發佈:2019-01-22
例如:appA要檢測啟動appB中的service
1.修改B中Service啟動時的FLAG
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
flags = START_STICKY;
return super.onStartCommand(intent, flags, startId);
}
2.新增B中Service銷燬時傳送自定義廣播
@Override
public void onDestroy() {
Intent intent = new Intent("com.app.custom");
sendBroadcast(intent);
super.onDestroy();
}
3.新增B中自定義許可權申明
<permission
android:name="app.custom.permission"
android:protectionLevel="signature" />
<uses-permission android:name="app.custom.permission" />
4.新增B中service的宣告
<service
android:name="com.appb.BService"
android:exported="true"//必須
android:permission="app.custom.permission">//三個屬性缺一不可
<intent-filter>
<!--action名字自定義,建議是xx.xx.xx形式-->
<action android:name="android.intent.action.START_B_SERVICE" />
</intent-filter >
</service>
5.新增A中許可權申明
<uses-permission android:name="app.custom.permission" />
6.新增A中監聽廣播
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
L.e("啟動B服務");
Intent intentNew = new Intent();
intentNew.setPackage("com.appb");
intentNew.setAction("android.intent.action.START_B_SERVICE");
context.startService(intentNew);
}
}
7.在A中註冊廣播
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="com.app.custom" />
</intent-filter>
</receiver>