Android 定制设备崩溃后app自动打开自身(应用保活功能,保持应用一直处于存活状态)

前几天,公司让我做一个功能,说是看门狗功能,我一脸懵了,因为,我才疏学浅,不知道啥意思,经过进一步了解吧,意思就是,应用在崩溃之后,能让应用在一定时间内自己启动自己本身的一个功能,当然,看了一下,还是有很多种做法的,我不一定有别人写的好,但是,我觉得,自己写出来也是一种成就,然后,我就自己稍微琢磨了下,原理呢,就是,开启服务,让服务循环检测自身应用是否存活着,如果存活就不做操作,如果不存活就开启应用,就是这么理解的,话不多说了,我就直接上代码吧 ,有问题的话,我就把代码也上传上去,有需要下载就是了

1、首先,我们创建一个服务,我给起了一个通俗易懂的名字KeepLiveService,字面就能理解,可以吧 然后呢,在里面进行判断应用存活状态,等等之类的,直接看代码吧,我也不多说了 ,

package com.example.demo.service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;


import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class KeepLiveService extends Service {

    private TimerTask task;
    private Timer timer;
    private Intent sevice;

    @Override
    public void onCreate() {
        super.onCreate();
        if (task != null) {
            task.cancel();
            task = null;
        }
        task = createVideoSchedulerTimer();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        timer = new Timer();
        long delay = 15000;
        long intevalPeriod = 15 * 1000;
        timer.schedule(task, delay, intevalPeriod);
    }

    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        if (intent == null) {
            startServices();
        }
        Notification notification = new Notification(R.mipmap.ic_launcher, "前台服务!应用包活!"
                , System.currentTimeMillis());
        //设置通知默认效果
        notification.flags = Notification.FLAG_SHOW_LIGHTS;
        startForeground(1, notification);
        return Service.START_STICKY;
    }


    private void startServices() {
        stopSelf();
        if (sevice == null)
            sevice = new Intent(this, KeepLiveService.class);
        startService(sevice);
    }

    private TimerTask createVideoSchedulerTimer() {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                //判断程序是否在运行
                boolean isRunning = isServiceStarted(getApplicationContext(), "com.example.pisplayer001");
                //没有运行就开启他
                if (!isRunning) {
                    Log.e("MyTestService", "程序未开启============");
//下面getLaunchIntentforPackage()里面的参数是你程序的报名,也就是,build.gradle里面的applicationId,所以,这里你要记得更改一下 
                    Intent intent = getPackageManager().getLaunchIntentForPackage("com.example.pisplayer001");
                    startActivity(intent);
                }
//                else {
//                    Log.e("MyTestService", "========程序已经运行了==========");
//                }
            }
        };
        return timerTask;
    }

    /**
     * 检测一个android程序是否在运行
     *
     * @param context
     * @param PackageName
     * @return
     */
    public static boolean isServiceStarted(Context context, String PackageName) {
        boolean isStarted = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(PackageName) && info.baseActivity.getPackageName().equals(PackageName)) {
                isStarted = true;
                break;
            }
        }
        return isStarted;
    }

    @Override
    public void onLowMemory() {
        startServices();
        super.onLowMemory();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        if (task != null) {
            task.cancel();
            task = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }
}

 

2、在AndroidManifest.xml的Application标签下,注册服务

  <service
            android:name=".service.KeepLiveService"
            android:enabled="true"
            android:exported="true"></service>

3、就是启动服务啦 ,在你需要开启服务的地方,也就是,程序主入口那里,进行开启,这样保证程序启动就开启服务,也就能一直检测这程序是否开启了 ,这里,有个地方说明一下,就是,程序自检的时候,我在里面备注了,要将自己的applicationId写上,上面是我自己的包名,你不更改是不能用的,所以要注意一下

    Intent seviceIntent = new Intent(this, KeepLiveService.class);
    startService(seviceIntent );

3、其次呢,其次呢,额,其次,其实就完成了,没了,就这些了 ,当你应用崩溃后,经过一定时间就能重启应用了,当然,你不能在你程序不稳定的情况下添加这个,在你测试结束后,如果没有出现问题,就添加上这个,如果出现突然的bug,应用不至于被杀死的状态,这样,不会造成不必要的麻烦了,应用的自启动时间,也就是,检测崩溃的时间,你可以设定,在程序里面,参数咋onCreat里面的  delay还有intevalPeriod,这两个参数,意思是delay是程序开启多长时间后,启动这个服务,intevalPeriod这个参数是,程序崩溃后,多长时间再进行自检,如果检测到程序崩溃了,就立即启动程序,下面是我上传的一个demo资源,不明白的话,就看一下吧,很简单 的

 

资源链接,点我,点我,有用的话给个赞,鼓励下我,谢谢

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值