The following is a summary of several methods to exit the program in Android. For more information, see.
The Android program has A lot of activities, such as the main window A, and calls the sub-window B. If you finish () directly in B, the next display is. In B, how does one close the entire Android application? I have summarized several simple implementation methods.
1. Local Dalvik VM Method
Copy codeThe Code is as follows:
Android. OS. Process. killProcess (android. OS. Process. myPid () // obtain the PID.
System. exit (0); // standard exit method of general java and c #. If the returned value is 0, the System Exits normally.
2. Task Manager Method
First, it must be noted that this method can run at the Android 1.5 API Level 3 or above and requires permissions.
Copy codeThe Code is as follows:
ActivityManager am = (ActivityManager) getSystemService (Context. ACTIVITY_SERVICE );
Am. restartPackage (getPackageName ());
The system will kill all processes and services under this package, and you will be able to kill them. You must add the permission android. permission. RESTART_PACKAGES.
3. According to the Activity declaration cycle
3. we know that the window class of Android provides A historical stack, and we can implement it skillfully through the stack principle. Here we add the Intent icon directly to window A when window A opens window B. FLAG_ACTIVITY_CLEAR_TOP. When B is enabled, all activities in the process space are cleared.
Use the following code to call window B in window:
Copy codeThe Code is as follows:
Intent intent = new Intent ();
Intent. setClass (Android123.this, CWJ. class );
Intent. setFlags (Intent. FLAG_ACTIVITY_CLEAR_TOP); // pay attention to the FLAG settings of the row.
StartActivity (intent );
Next, use the finish method to exit all the services in window B.
4. customize an Actiivty stack. The same principle is true. However, an Activity stack in singleton mode is used to manage all activities. And provides the method to exit all activities. The Code is as follows:
Copy codeThe 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;
}
// Exit the stack top Activity
Public void popActivity (Activity activity ){
Activity. finish ();
ActivityStack. remove (activity );
Activity = null;
}
}
// Obtain the Activity at the top of the current stack
Public Activity currentActivity (){
Activity activity = activityStack. lastElement ();
Return activity;
}
// Push the current Activity into the stack
Public void pushActivity (Activity activity ){
ActivityStack = new Stack ();
}
ActivityStack. add (activity );
}
// Exit all activities in the stack
Public void popallactivityeffectone (Class cls ){
While (true ){
Activity activity = currentActivity ();
Break;
}
Break;
}
PopActivity (activity );
}
}
}