例如: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>