Summary of several methods for Android exit program

  • 2020-05-17 06:28:36
  • OfStack

The Android program has many Activity, such as the main window A, which calls the child window B. If finish() is directly displayed in B, A is displayed next. How do I close the entire Android application in B? I summarized several relatively simple implementation methods.
1. Local methods for Dalvik VM


android.os.Process.killProcess(android.os.Process.myPid()) // To obtain PID
System.exit(0); // conventional java , c# Is the standard exit method, and the return value is 0 Represents normal exit 

2. The task manager method
The first thing to note is that this method runs on Android 1.5 API Level 3 or more, and requires permissions

ActivityManager am = (ActivityManager)getSystemService (Context.ACTIVITY_SERVICE);
am.restartPackage(getPackageName());

The system is going to kill all the processes, all the services that are in this package, and it's going to kill them, and it's going to kill them, and it's going to add the permission android.permission.RESTART_PACKAGES

3. According to the declaration cycle of Activity
3. We know that Android's window class provides a history stack, which we can implement through the principle of stack. Here, when A window opens B window, Intent.FLAG_ACTIVITY_CLEAR_TOP, Intent.FLAG_ACTIVITY_CLEAR_TOP, B will clear all Activity in the process space.
Call the B window in the A window using the following code


Intent intent = new Intent();
intent.setClass(Android123.this, CWJ.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // Line minded FLAG Set up the 
startActivity(intent);

Then, when you need to exit from the B window, you can exit completely by using the finish method.

4. Customize 1 Actiivty stack, same as above, but use 1 singleton mode Activity stack to manage all Activity. It also provides a way to exit all Activity. The code is as follows:


public class ScreenManager {
private static Stack activityStack;
private static ScreenManager instance;
private ScreenManager(){
}
public static ScreenManager getScreenManager(){
instance=new ScreenManager();
}
return instance;
}
// Out of the top Activity
public void popActivity(Activity activity){
activity.finish();
activityStack.remove(activity);
activity=null;
}
}
// Gets the current top of the stack Activity
public Activity currentActivity(){
Activity activity=activityStack.lastElement();
return activity;
}
// The current Activity Push the stack 
public void pushActivity(Activity activity){
activityStack=new Stack();
}
activityStack.add(activity);
}
// Exit all in the stack Activity
public void popAllActivityExceptOne(Class cls){
while(true){
Activity activity=currentActivity();
break;
}
break;
}
popActivity(activity);
}
}
}


Related articles: