SoFunction
Updated on 2025-03-11

Android ActivityManager usage case details

Preface

Activity can obtain running application information, servcie, process, app, memory, Task information, etc.

Get information


  1. Important fields in MemoryInfo: availMem (system available memory), totalMem (total memory), threshold (low memory threshold, i.e. the critical line of low memory), lowMemory (whether it is a low memory state)

  2. Mainly used to obtain memory information in the process.

  3. Encapsulates the information of the running process, related fields: processName (process name), pid (process pid), uid (process uid), pkgList (all packages under this process).

  4. Used to encapsulate the running service information, but in addition to the service process information, there are some other information, activeSince (time and method of activation for the first time), and foreground (whether the service is executed in the background).

  5. Used to encapsulate Task information, including id (the unique identity of the task), baseActivity (the basic Activity of the task stack), topActivity (the Activity at the top of the task stack), numActivities (the number of activities in the task stack), description (the current status description of the task), etc.

Common methods of ActivityManager

  • clearApplicationUserData(): used to clear user data, which is equivalent to clear user data in mobile settings.
  • addAppTask (Activity activity, Intent intent, description, Bitmap thumbnail) : Create a new task stack for the Activity, activity (the activity that needs to be created for the task stack), intent (the Intent used to jump to the page), description (description information), thumbnail (thumbnail)
  • getDeviceConfigurationInfo (): Get device information
  • getLauncherLargeIconSize () : Get the Launcher icon size
  • getMemoryInfo (outInfo): Get the current memory information of the system
  • getProcessMemoryInfo(): Returns the situation where one or more processes use memory
  • getRunningAppProcesses(): Get the list of application processes on the device
  • getAppTasks(): Get the current application task list
  • isUserAMonkey(): Whether the user is a monkey, used to determine whether the keyboard is randomly pressed
  • killBackgroundProcesses(String packageName): Kill the corresponding process according to the package name
  • getRunningTasks (int maxNum): Get the list of running tasks
  • getRecentTasks (int maxNum, int flags): Get the user-started task list
  • getMyMemoryState (outState): Get the global memory state of the process

Determine whether the application is running in the foreground and whether the application is running

//Discern whether the application is running in the foregroundpublic boolean isRunningForeground(Context context){
        String packageName=getPackageName(context);
        String topActivityClassName=getTopActivityName(context);
        ("packageName="+packageName+",topActivityClassName="+topActivityClassName);
        if (packageName!=null&&topActivityClassName!=null&&(packageName)) {
            ("App executes in the foreground");
            return true;
        } else {
            ("App executes in the background");
            return false;
        }
    }

// Determine whether the application is runningpublic boolean isRun(Context context,String mPackageName){
        ActivityManager am = (ActivityManager)(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = (100);
        boolean isAppRunning = false;
        //100 indicates the maximum number of tasks to be taken, indicating the currently running Activity, indicating that this process is running in the system background.        for (RunningTaskInfo info : list) {
            if (().equals(mPackageName) || ().equals(mPackageName)) {
                isAppRunning = true;
                ("ActivityService",() + " ()="+());
                break;
            }
        }
        if(isAppRunning){
            ("ActivityService", "The program is running");
        }else{
            ("ActivityService", "The program is not running");
        }
        return isAppRunning;
}

//Get the ActivityName on the top of the stackpublic  String getTopActivityName(Context context){
        String topActivityClassName=null;
         ActivityManager activityManager =
        (ActivityManager)((.ACTIVITY_SERVICE )) ;
         List<runningtaskinfo> runningTaskInfos = (1) ;
         if(runningTaskInfos != null){
             ComponentName f=(0).topActivity;
             topActivityClassName=();
         }
         return topActivityClassName;
    }

    public String getPackageName(Context context){
         String packageName = ();  
         return packageName;
    }

Customize ActivityManager Management Activity

We need to define our own ActivityManager, and put the started Activity into the stack in the OnCreate method in BaseActivity through our customized ActivityManager, and unstack the Activity in the onDestroy method.

/**
  * Used to manage activities and obtain activities
  * After ending an activity, you should determine whether the current stack is empty. If it is empty, the reference of this class is set to null to facilitate the virtual machine to recycle memory.
  * Singleton, call {@link #getActivityManager()} to get the instance
  * Member variable {@link #mActivityStack} should be consistent with the system's fallback stack, so it must be in its onCreate when starting the activity.
  * Add this activity to the top of the stack. At the end of the activity, the activity must be out of the stack in onDestroy.
  */

public class ActivityManager {

    private static ReStack<Activity> mActivityStack;    //Activity stack    private static ActivityManager mInstance;

    private ActivityManager() {
        mActivityStack = new ReStack<>();
    }

    /**
      * Get a singleton of ActivityManager.
      *
      * @return ActivityManager instance
      */
    public static ActivityManager getActivityManager() {
        if (mInstance == null) {
            mInstance = new ActivityManager();
        }
        return mInstance;
    }

    /**
      * Add an activity to the top of the stack.
      *
      * @param activity Added activity
      */
    public void pushActivity(Activity activity) {
        if (mActivityStack == null) {
            mActivityStack = new ReStack<>();
        }
        (activity);
    }

    /**
      * Get the top of the stackActivity.
      *
      * @return If the stack exists, return to the activity at the top of the stack
      */
    public Activity peekActivity() {
        if (mActivityStack != null && !()) {
            return ();
        } else {
            return null;
        }
    }

    /**
      * End the current activity and call it in the onDestroy of the activity.
      */
    public void popActivity() {
        if (mActivityStack != null && !()) {
            ();
        }
        //If the stack becomes empty after removing an activity, cancel the reference of this class to facilitate the virtual machine to recycle        if (mActivityStack != null && ()) {
            mInstance = null;
        }
    }

    /**
      * End the activity of the matching class name closest to the top of the stack.
      * What you traversed does not necessarily end. The traversal starts from the bottom of the stack, in order to determine that there is this activity in the stack and obtain a reference
      * Delete is the first one found from the top of the stack.
      * Called when ending activity outside the activity
      *
      * @param klass class name
      */
    public void popActivity(Class<? extends BaseActivity> klass) {
        for (Activity activity : mActivityStack) {
            if (activity != null && ().equals(klass)) {
                ();
                break;              //Only one            }
        }
    }

    //Remove all activities    public void removeAll(){
        for (Activity activity : mActivityStack) {
            if (activity != null) {
                ();
                break;              
            }
        }
    }
}

This is the end of this article about the detailed explanation of Android ActivityManager usage cases. For more information about Android ActivityManager usage, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!