1. finish() method
This method can end the current Activity, but if your App has a lot of activities, it's a bit stretched.
In addition, there is a method called finishActivity (int request Code). For this method, first look at the api description of sdk.
- public void finishActivity (int requestCode)
- Since: API Level 1
- Force finish another activity that you had previously started with startActivityForResult(Intent, int).
- Parameters requestCode The request code of the activity that you had given to startActivityForResult(). If there are multiple activities started with this request code, they will all be finished.
You might understand that Activity 1 starts Activity 2 with method startActivity ForResult (Intent, int) and ends Activity 1 with method finishActivity (int request Code) in Activity 2, but unfortunately, that's not the case. Don't believe you can Demo!
It is clear from the above document that this method forces the closure of Activeness initiated by the method startActivityForResult (Intent, int). That is to say, the method onActivityResult (int request Code, int resultCode, Intent data) in Activity1 receives the results returned by Activity2, and finishActivity (int request Code) must be invoked in Activity1 to end Activity2. . (Generally in onActivity Result Method calls this method to end Activity2.
- Force finish another activity that you had previously started with startActivityForResult(Intent, int).
- Parameters
Also, the following two methods, you can refer to the documentation and source code research.
- finishActivityFromChild(Activity child, int requestCode)
- finishFromChild(Activity child)
2. killProcess
By calling Android The relevant method of. os.Process, end App, example is as follows:
- btn_exit.setOnClickListener(new Button.OnClickListener() {
- @Override
- public void onClick(View v) {
- android.os.Process.killProcess(android.os.Process.myPid());
- }
- });
3. exit
We know that, Java The exit(int code) method of the method can exit the program. By looking at the source code of the method, we know that it actually calls the following method:
- Runtime.getRuntime().exit(code);
Sample code, as follows:
- btn_exit.setOnClickListener(new Button.OnClickListener() {
- @Override
- public void onClick(View v) {
- System.exit(0);//Exit App Normally
- }
- });
Next, we will study this method. The method jdk of java.lang.System class illustrates:
- exit
- public static void exit(int status)
- Terminate the currently running Java virtual machine. Parameters are used as status codes; conventionally, non-zero status codes indicate abnormal termination.
- This method calls the exit method in the Runtime class. This method will never return normally.
- Calling System.exit(n) is actually equivalent to calling:
- Runtime.getRuntime().exit(n)
- Parameters:
- Status - Exit status.
- Throw out:
- SecurityException - If the security manager exists and its checkExit method does not allow exit in a specified state.
- See also:
- Runtime.exit(int)
That is to say, if the parameter is non-zero, it is an exception to exit the program. If the parameter is 0, it will exit normally.
Look at the source code for this method of the RunTime class:
- publicvoid exit(int status) {
- SecurityManager security = System.getSecurityManager();
- if (security !=null) {
- security.checkExit(status);
- }
- Shutdown.exit(status);
- }
Its api description:
- exit
- public void exit(int status)
- Terminate the currently running Java virtual machine by starting the closing sequence of the virtual machine. This method returns from the abnormal. Variables can be treated as status codes; conventionally, non-zero status codes represent abnormal termination.
- The closing sequence of virtual machines consists of two stages. In the first phase, all registered closed hooks (if any) are started in an unspecified order and allowed to run simultaneously until the end. In the second phase, if exit finalization is enabled, all uncalled finalization methods are run. Once this stage is completed, the virtual machine will pause.
- If this method is called after the virtual machine has started its closing sequence, it will be blocked indefinitely if the closing hook is running. If the shutdown hook has been run and on-exit finalization is enabled, this method will suspend the virtual machine with a given state code (if the state code is non-zero); otherwise, the virtual machine will be blocked indefinitely.
- System.exit method is a traditional and convenient way to call this method.
- Parameters:
- Status - Termination status. By convention, a non-zero status code indicates an abnormal termination.
- Throw out:
- SecurityException - If the security manager exists and its checkExit method does not allow the specified state to exist
- See also:
- SecurityException, SecurityManager.checkExit(int), addShutdownHook(java.lang.Thread), removeShutdownHook(java.lang.Thread), runFinalizersOnExit(boolean), halt(int)
This method also calls the Shutdown class exit() method.
- staticvoid exit(int status) {
- boolean runMoreFinalizers =false;
- synchronized (lock) {
- if (status !=0) runFinalizersOnExit =false;
- switch (state) {
- case RUNNING: /* Initiate shutdown */
- state = HOOKS;
- break;
- case HOOKS: /* Stall and halt */
- break;
- case FINALIZERS:
- if (status !=0) {
- /* Halt immediately on nonzero status */
- halt(status);
- }else {
- /* Compatibility with old behavior:
- * Run more finalizers and then halt
- */
- runMoreFinalizers = runFinalizersOnExit;
- }
- break;
- }
- }
- if (runMoreFinalizers) {
- runAllFinalizers();
- halt(status);
- }
- synchronized (Shutdown.class) {
- /* Synchronize on the class object, causing any other thread
- * that attempts to initiate shutdown to stall indefinitely
- */
- sequence();
- halt(status);
- }
- }
runAllFinalizers() is a local method:
- JNIEXPORTvoid JNICALL
- Java_java_lang_Shutdown_runAllFinalizers(JNIEnv *env, jclass ignored)
- {
- jclass cl;
- jmethodID mid;
- if ((cl = (*env)->FindClass(env,"java/lang/ref/Finalizer"))
- && (mid = (*env)->GetStaticMethodID(env, cl,
- "runAllFinalizers","()V"))) {
- (*env)->CallStaticVoidMethod(env, cl, mid);
- }
- }
The parameter of System.exit() is to return the reason for the exit to the system, which can generally be any integer.
0 denotes normal exit and 1 denotes abnormal exit.
Finally, the difference between finish() and exit methods is discussed.
Fini () is a class method of Activity. It only aims at Activity. When calling finish(), it only pushes the activity to the background, does not release memory immediately, and the resources of the activity are not cleaned up. When calling System.exit(0), it exits the current activity and releases resources (memory), but this method can not end the whole App, such as multiple Activty or other component service, etc. It will end.
actually android The mechanism makes it impossible for users to quit the application completely. When your application has not been used for the longest time, android itself decides to shut down the application.
4. restartPackage method
- ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
- manager.restartPackage(getPackageName());
First you need to create an ActivityManager object, and then call the restartPackage() method (if you are interested, you can see the source code).
Note: getPackageName gets the current application package name, such as mark.zhang
To exit App in this way, you need permissions:
- <uses-permissionandroid:name="android.permission.RESTART_PACKAGES"/>
More detailed explanation is as follows:
- void android.app.ActivityManager.restartPackage(String packageName)
- Have the system perform a force stop of everything associated with the given application package. All processes that share its uid will be killed, all services it has running stopped, all activities removed, etc. In addition, a Intent.ACTION_PACKAGE_RESTARTED broadcast will be sent, so that any of its registered alarms can be stopped, notifications removed, etc.
- You must hold the permission android.Manifest.permission.RESTART_PACKAGES to be able to call this method.
- Parameters:
- packageName The name of the package to be stopped.
As you can see, the process of the same UID will be kill ed, the related services will be stopped, all activities will be removed, and a broadcast will be sent.
Note that after Android 2.2, this method can't end the application. It needs to use the following method of the ActivityManager class:
- publicvoid killBackgroundProcesses (String packageName)
The api documentation is clear:
- public void restartPackage (String packageName)
- Since: API Level 3
- This method is deprecated.
- This is now just a wrapper for killBackgroundProcesses(String); the previous behavior here is no longer available to applications because it allows them to break other applications by removing their alarms, stopping their services, etc.
In addition, permissions are required:
- <uses-permissionandroid:name="android.permission.KILL_BACKGROUND_PROCESSES"/>
But no matter how you toss and turn, you still can't quit App. Whoop! Here we give a method:
- int currentVersion = android.os.Build.VERSION.SDK_INT;
- if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) {
- Intent startMain =new Intent(Intent.ACTION_MAIN);
- startMain.addCategory(Intent.CATEGORY_HOME);
- startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- startActivity(startMain);
- System.exit(0);
- }else {// android2.1
- ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
- am.restartPackage(getPackageName());
- }
For android.os.Build.VERSION.SDK_INT, you can refer to http://blog.csdn.net/androidbluetooth/article/details/6778422
5. summary
finish(): Ending the current Activity does not immediately release memory. Follow the android memory management mechanism.
exit(): End the current component, such as Activity, and immediately release the resources occupied by the current Activity.
killProcess(): End the current component, such as Activity, and immediately release the resources occupied by the current Activity.
Restart Package (): Ends the entire App, including other Activity components such as service.
Special note: Except that the finish() method can call Activity's life cycle methods such as onStop() and onDestroy(), the other three exit App s will not call Activity's life cycle methods. Unless the Activity lifecycle method is actively invoked before or after these methods are invoked. Such as:
- System.exit(int);
- onDestroy();