根据包名检测APP运行状态

Android检测Activity或者Service是否运行的方法

目录

1.定义一个监控服务

2.注册双进程Service

3.检测是否活着的工具类CheckUtil

4.新建MainActivity,启动监控服务

5.加入开机自启动

6.在AndroidManifest.xml配置MainActivity和服务

7.项目代码:



有些情况,比如工业应用:数据的监测和收集,需要app一直运行,即使遇到异常崩溃,也要立即重启。我们用一个后台服务来监测这个app的运行情况。如果这个app被人为退出了,或者遇到bug崩溃了,就要重新启动,免得丢失数据。

项目的结构:

根据包名检测APP运行状态_第1张图片

1.定义一个监控服务

package com.monitoringservice;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.util.Log;



import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;


/**
 * Created by xpf on 2017/6/3 :)
 * 检测APP页面是否一直运行,不运行就直接启动
 * Android检测Activity或者Service是否运行的方法_Android_脚本之家
 * https://www.jb51.net/article/136953.htm
 */

public class MonitoringService extends Service {

    private final static String TAG = "MonitoringService";

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("kill_self".equals(intent.getAction())) {
                Log.e(TAG, "onReceive:杀死自己的进程!");
                killMyselfPid(); // 杀死自己的进程
            }
        }
    };

    private Timer timer = new Timer();
    private TimerTask task = new TimerTask() {
        @Override
        public void run() {
            checkIsAlive();
        }
    };

    /**
     * 检测应用是否活着
     */
    private void checkIsAlive() {
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA).format(new Date());
        Log.v(TAG, "CustodyService Run: " + format);
        //检测自己,启动自己
/*        boolean AIsRunning =   CheckUtil.isClsRunning(MonitoringService.this,"com.monitoringservice","com.monitoringservice.MainActivity");
        Log.v(TAG, "AIsRunning Run: " + AIsRunning);
        if(!AIsRunning){//如果界面挂掉直接启动MainActivity
            Intent intent = new Intent();
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setClass(MonitoringService.this, MainActivity.class);
            startActivity(intent);
        }*/
         //假设要检测的应用包名为:  com.uarttest.www,  检测应用的主页面是否在运行
        boolean AIsRunning =   CheckUtil.isClsRunning(MonitoringService.this,"com.uarttest.www","com.uarttest.www.MainActivity");
        Log.v(TAG, "AIsRunning Run: " + AIsRunning);
        if(!AIsRunning){//如果界面挂掉直接启动应用
            //根据包名启动应用
            Intent intent = new Intent();
            PackageManager packageManager = getPackageManager();
            intent =packageManager.getLaunchIntentForPackage("com.uarttest.www");
            startActivity(intent);
        }
/*        boolean AIsRunning = CheckUtil.isClsRunning(MonitoringService.this, "com.xpf.monitor", "com.xpf.monitor.activity.AActivity");
        boolean BIsRunning = CheckUtil.isClsRunning(MonitoringService.this, "com.xpf.monitor", "com.xpf.monitor.activity.BActivity");
        boolean b = (AIsRunning || BIsRunning);
        boolean CIsRunning = CheckUtil.isClsRunning(MonitoringService.this, "com.xpf.monitor", "com.xpf.monitor.activity.CActivity");

        Log.e(TAG, "AIsRunning || BIsRunning is running:" + b + ",CIsRunning:" + CIsRunning);

        if (!CIsRunning) {
            if (!b) { //如果界面挂掉直接启动AActivity
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setClass(MonitoringService.this, AActivity.class);
                startActivity(intent);
            }
        }*/
    }


    @Override
    public void onCreate() {
        super.onCreate();
        Log.v(TAG, "onCreate: 启动监控服务! ");
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("kill_self");
        registerReceiver(broadcastReceiver, intentFilter);
        timer.schedule(task, 0, 10000);// 设置检测的时间周期(毫秒数)
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

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

    /**
     * 杀死自身的进程
     */
    private void killMyselfPid() {
        int pid = android.os.Process.myPid();
        String command = "kill -9 " + pid;
        Log.e(TAG, "killMyselfPid: " + command);
        stopService(new Intent(MonitoringService.this, MonitoringService.class));
        try {
            Runtime.getRuntime().exec(command);
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

 

2.注册双进程Service

        
            
                
            
        

3.检测是否活着的工具类CheckUtil

package com.monitoringservice;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.text.TextUtils;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class CheckUtil {
    private final static String TAG = "MonitoringService";
    //检测service是否在运行
    public static boolean isServiceWorked(Context context, String serviceName) {
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList runningService = (ArrayList) myManager.getRunningServices(Integer.MAX_VALUE);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    //检测activity是否存在再栈顶
    public static boolean isForeground(Context context, String PackageName) {
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List task = myManager.getRunningTasks(1);
        ComponentName componentInfo = task.get(0).topActivity;
        final String packageName = componentInfo.getPackageName();
        Log.v(TAG, "packageName: " + packageName);
        if (packageName.equals(PackageName))
            return true;
        return false;
    }

    /**
     * 判断某个app进程是否在运行
     *
     * @param context
     * @param appInfo
     * @return
     */
    public static boolean isRunningProcess(Context context, String appInfo) {
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List runningAppPs = myManager.getRunningAppProcesses();
        if (runningAppPs != null && runningAppPs.size() > 0) {
            if (runningAppPs.contains(appInfo)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断一个Activity是否正在运行
     *
     * @param pkg  pkg为应用包名
     * @param cls  cls为类名eg
     * @param context
     * @return
     */
    public static boolean isClsRunning(Context context, String pkg, String cls) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List tasks = am.getRunningTasks(1);
        ActivityManager.RunningTaskInfo task = tasks.get(0);
        if (task != null) {
            return TextUtils.equals(task.topActivity.getPackageName(), pkg) &&
                    TextUtils.equals(task.topActivity.getClassName(), cls);
        }
        return false;
    }
}

4.新建MainActivity,启动监控服务

package com.monitoringservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

/**
 * Android检测Activity或者Service是否运行的方法_Android_脚本之家
 * https://www.jb51.net/article/136953.htm
 */
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startService();
    }

    /**
     * 启动服务
     */
    private void startService() {
        Intent intent = new Intent(MainActivity.this, MonitoringService.class);
        intent.setAction("android.intent.action.RESPOND_VIA_MESSAGE");
        startService(intent);
    }
}

5.加入开机自启动

6.在AndroidManifest.xml配置MainActivity和服务


    
    

    

        
            
                
            
        



7.项目代码:

根据包名检测APP运行状态 开机自动检测-源码

你可能感兴趣的:(android,service)