Implement activity manager to exit all activity at once

  • 2020-05-24 06:05:32
  • OfStack

There are many different ways to log out of all Activity at once, such as by killing the process: android.os.Process.killProcess (android.os.Process.myPid ()); This approach requires the addition of permissions android.permission.KILL_BACKGROUND_PROCESSES;
Or use System. exit (0); To exit.

The other method is ActivityManager's restartPackage() method. But I tried, and it didn't work...

Others say that letting a program throw an exception and exit is something we strongly recommend against. There are other methods, such as broadcasting all Activity when exiting.

One method that I personally recommend is to customize an Activity manager to manage all the Activity that have been opened, and then exit all Activity through this manager when you want to exit. It has been proved that this method is feasible and works very well.

Here is a simple Activity manager code that basically sets up a stack and pushes each open Activity onto the stack. Take them out in turn as you exit.


public class MyActivityManager {
private static MyActivityManager instance;
private Stack<Activity> activityStack;//activity The stack 
private MyActivityManager() {
}
// The singleton pattern 
public static MyActivityManager getInstance() {
    if (instance == null) {
        instance = new MyActivityManager();
    }
    return instance;
}
// the 1 a activity Pressure into the stack 
public void pushOneActivity(Activity actvity) {
    if (activityStack == null) {
        activityStack = new Stack<Activity>();
    }
    activityStack.add(actvity);
    Log.d("MyActivityManager ", "size = " + activityStack.size());
}
// Gets the top of the stack activity First in, then out 
public Activity getLastActivity() {
    return activityStack.lastElement();
}
// remove 1 a activity
public void popOneActivity(Activity activity) {
    if (activityStack != null && activityStack.size() > 0) {
        if (activity != null) {
            activity.finish();
            activityStack.remove(activity);
            activity = null;
        }
    }
}
// Out of all activity
public void finishAllActivity() {
    if (activityStack != null) {
        while (activityStack.size() > 0) {
            Activity activity = getLastActivity();
            if (activity == null) break;
            popOneActivity(activity);
        }
    }
}}

The push method is called in every onCreate method in activity to push the current activity into the management stack. For example, in MainActivity:
MyActivityManager mam = MyActivityManager.getInstance();
mam. pushOneActivity (MainActivity. this); It pushes the current activity onto the stack. Exit all activ by calling the exit all Activity method at the exit place of all Activity


Related articles: