【Android】一个APP检测另一个APP的Service被杀死时自动重启服务

例如: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>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值