Detailed explanation of the method of Android development to determine whether an app application is running

This article describes the method of Android development to determine whether an app application is running. Share it with everyone for your reference, as follows:

In an application, or a Service or Receiver, sometimes it is necessary to determine whether an application is running in order to perform some related processing. At this time, we need to get an ActivityManager. This Manager, as the name implies, manages the Activity. It has a method called getRunningTasks, you can get the list of Tasks currently running in the system, the code is as follows:

ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> list = am.getRunningTasks(100);
for (RunningTaskInfo info : list) {
  if (info.topActivity.getPackageName().equals(MY_PKG_NAME) && info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
    isAppRunning = true;
    //find it, break
    break;
  }
}

100 represents the maximum number of tasks to be fetched, and info.topActivityrepresents the currently running Activity, indicating info.baseActivitythat this process is running in the background of the system. How to judge specifically depends on your own business needs. There are more methods in this class to obtain the services running on the system, memory usage, etc. Please find them yourself.

One thing to note, if you want to run this method normally, please add in your AndroidManifest.xml:

<uses-permission android:name="android.permission.GET_TASKS" />

For details on Android Manifest permission control, please refer to Android Manifest Function and Permission Description

/**
* 判断应用是否在运行
* @param context
* @return
*/
public boolean isRun(Context context){
    ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> list = am.getRunningTasks(100);
    boolean isAppRunning = false;
    String MY_PKG_NAME = "com.ad";
    //100表示取的最大的任务数,info.topActivity表示当前正在运行的Activity,info.baseActivity表系统后台有此进程在运行
    for (RunningTaskInfo info : list) {
      if (info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName().equals(MY_PKG_NAME)) {
        isAppRunning = true;
        Log.i("ActivityService isRun()",info.topActivity.getPackageName() + " info.baseActivity.getPackageName()="+info.baseActivity.getPackageName());
        break;
      }
    }
    Log.i("ActivityService isRun()", "com.ad 程序  ...isAppRunning......"+isAppRunning);
    return isAppRunning;
}

APIs related to the internal state information of the Android system:

Get ActivityManager:

ActivityManager activityManager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE)
ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();

Get information about the memory state of a process:

Debug.MemoryInfo[] processMemoryInfo = activityManager.getProcessMemoryInfo(processIds)

Get information about the currently running service:

List<RunningServiceInfo> runningServiceInfos = activityManager.getRunningServices(MaxValue);

Get information about the currently running task:

List<RunningTaskInfo> runningTaskInfos = activityManager.getRunningTasks(MaxValue);

Among them, the topActivity of runningTaskInfos is the active activity of the current task. In the getRunningTasks()returned task queue, the system will sort according to the activity of these tasks, the more active the higher the front. The first is the currently active Task

/**
* 检测某ActivityUpdate是否在当前Task的栈顶
*/
public boolean isTopActivy(String cmdName){
    ActivityManager manager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
    List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(1);
    String cmpNameTemp = null;
    if(null != runningTaskInfos){
        cmpNameTemp=(runningTaskInfos.get(0).topActivity).toString);
        Log.e("cmpname","cmpname:"+cmpName);
    }
    if(null == cmpNameTemp)return false;
    return cmpNameTemp.equals(cmdName);
}
/**get the launcher status */
private boolean isLauncherRunnig(Context context) {
   boolean result = false ;
   List<String> names = getAllTheLauncher();
   ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE) ;
   List<ActivityManager.RunningAppProcessInfo> appList = mActivityManager.getRunningAppProcesses() ;
   for (RunningAppProcessInfo running : appList) {
     if (running.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
       for (int i = 0; i < names.size(); i++) {
         if (names.get(i).equals(running.processName)) {
           result = true ;
           break;
         }
       }
     }
   }
   return result ;
}
/**
* 得到所有的Launcher
*/
private List<String> getAllTheLauncher(){
    List<String> names = null;
    PackageManager pkgMgt = this.getPackageManager();
    Intent it = new Intent(Intent.ACTION_MAIN);
    it.addCategory(Intent.CATEGORY_HOME);
    List<ResolveInfo> ra =pkgMgt.queryIntentActivities(it,0);
    if(ra.size() != 0){
      names = new ArrayList<String>();
    }
    for(int i=0;i< ra.size();i++)
    {
    String packageName = ra.get(i).activityInfo.packageName;
    names.add(packageName);
    }
    return names;
}

Android takes the currently displayed activity:

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
Log.d("", "pkg:"+cn.getPackageName());
Log.d("", "cls:"+cn.getClassName());

How does Android determine whether a program is running in the foreground:

private boolean isTopActivity(){
    List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
    if(tasksInfo.size() > 0){
      //应用程序位于堆栈的顶层
      if(packageName.equals(tasksInfo.get(0).topActivity.getPackageName())){
        return true;
      }
    }
    return false;
}

Readers who are interested in more Android-related content can check out the topics on this site: "Introduction and Advanced Tutorials for Android Development", "Summary of Android Debugging Skills and Common Problem Solving Methods", "Summary of Usage of Android Basic Components", "Android View View Summary of Skills", "Summary of Android Layout Layout Skills" and "Summary of Usage of Android Controls"

I hope that this article will be helpful to everyone's Android programming.

Reprinted in: Android development method to determine whether an app is running in detail / Zhang Shengrong

Guess you like

Origin blog.csdn.net/weixin_42602900/article/details/129682714