进程保活之单进程守护

实际项目中,保证进程不被完全彻底杀死,是不可能的。
单进程守护场景:home键,直接杀死进程,进程仍然处于运行状态;
适用手机类型:50%的低中端手机,小米做的太好了,根本无法实现。
单进程守护原理:应用启动开启一个service,并在service的onDestroy()方法里发送广播,BroadcastReccevier里重新startService;
代码实现:
1、创建Service服务:

    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startTime();
        //返回值设置,保证后台一直运行;
        return START_STICKY;
    }
    /**
     * 当进程被销毁时,发送广播重启服务。
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Intent broadCastIntent=new Intent("com.example.xiaoke.singleservice.ServiceRestartBroadCastReceiver.restart");
        sendBroadcast(broadCastIntent);
        stopTime();
    }

2、创建braodCastRecevier,接收到广播重启服务:

  @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG,"onReceive");
        context.startService(new Intent(context,RecreatService.class));
    }

3、清单文件配置:

  <service
            android:name=".RecreatService"
            android:enabled="true"
            android:exported="true"></service>
        <receiver
            android:name=".ServiceRestartBroadCastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                    <action android:name="com.example.xiaoke.singleservice.ServiceRestartBroadCastReceiver.restart"></action>
            </intent-filter>
        </receiver>

ok项目结束,实际测试一下。关于源码,请留下邮箱。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值