android shuts down the application completely

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.

  1. public void finishActivity (int requestCode) 
  2. Since: API Level 1 
  3. Force finish another activity that you had previously started with startActivityForResult(Intent, int). 
  4. 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.

  1. Force finish another activity that you had previously started with startActivityForResult(Intent, int). 
  2. Parameters 

Also, the following two methods, you can refer to the documentation and source code research.

  1. finishActivityFromChild(Activity child, int requestCode) 
  2. finishFromChild(Activity child) 

2. killProcess

By calling Android The relevant method of. os.Process, end App, example is as follows:

  1. btn_exit.setOnClickListener(new Button.OnClickListener() { 
  2.     @Override 
  3.     public void onClick(View v) { 
  4.         android.os.Process.killProcess(android.os.Process.myPid()); 
  5.     } 
  6.       }); 

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:

  1. Runtime.getRuntime().exit(code); 

Sample code, as follows:

  1. btn_exit.setOnClickListener(new Button.OnClickListener() { 
  2.            @Override 
  3.            public void onClick(View v) { 
  4.                 System.exit(0);//Exit App Normally 
  5.             } 
  6.         }); 

Next, we will study this method. The method jdk of java.lang.System class illustrates:

  1. exit 
  2.  
  3. public static void exit(int status) 
  4. Terminate the currently running Java virtual machine. Parameters are used as status codes; conventionally, non-zero status codes indicate abnormal termination.  
  5. This method calls the exit method in the Runtime class. This method will never return normally.  
  6.  
  7. Calling System.exit(n) is actually equivalent to calling:
  8.  
  9. Runtime.getRuntime().exit(n) 
  10.   
  11. Parameters:
  12. Status - Exit status.  
  13. Throw out:
  14. SecurityException - If the security manager exists and its checkExit method does not allow exit in a specified state.  
  15. See also:
  16. 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:

  1. publicvoid exit(int status) { 
  2.         SecurityManager security = System.getSecurityManager(); 
  3.     if (security !=null) { 
  4.         security.checkExit(status); 
  5.     } 
  6.     Shutdown.exit(status); 

Its api description:

  1. exit 
  2.  
  3. public void exit(int status) 
  4. 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.  
  5. 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.  
  6.  
  7. 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.  
  8.  
  9. System.exit method is a traditional and convenient way to call this method.  
  10.  
  11. Parameters:
  12. Status - Termination status. By convention, a non-zero status code indicates an abnormal termination.  
  13. Throw out:
  14. SecurityException - If the security manager exists and its checkExit method does not allow the specified state to exist
  15. See also:
  16. 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.

  1. staticvoid exit(int status) { 
  2.     boolean runMoreFinalizers =false
  3.     synchronized (lock) { 
  4.        if (status !=0) runFinalizersOnExit =false
  5.        switch (state) { 
  6.        case RUNNING:  /* Initiate shutdown */ 
  7.         state = HOOKS; 
  8.        break
  9.        case HOOKS:    /* Stall and halt */ 
  10.        break
  11.        case FINALIZERS: 
  12.        if (status !=0) { 
  13.            /* Halt immediately on nonzero status */ 
  14.             halt(status); 
  15.         }else
  16.            /* Compatibility with old behavior:
  17.              * Run more finalizers and then halt
  18.              */ 
  19.             runMoreFinalizers = runFinalizersOnExit; 
  20.         } 
  21.        break
  22.         } 
  23.     } 
  24.     if (runMoreFinalizers) { 
  25.         runAllFinalizers(); 
  26.         halt(status); 
  27.     } 
  28.     synchronized (Shutdown.class) { 
  29.        /* Synchronize on the class object, causing any other thread
  30.              * that attempts to initiate shutdown to stall indefinitely
  31.          */ 
  32.         sequence(); 
  33.         halt(status); 
  34.     } 
  35.     } 

runAllFinalizers() is a local method:

  1. JNIEXPORTvoid JNICALL 
  2. Java_java_lang_Shutdown_runAllFinalizers(JNIEnv *env, jclass ignored) 
  3.     jclass cl; 
  4.     jmethodID mid; 
  5.  
  6.     if ((cl = (*env)->FindClass(env,"java/lang/ref/Finalizer")) 
  7.     && (mid = (*env)->GetStaticMethodID(env, cl, 
  8.                        "runAllFinalizers","()V"))) { 
  9.     (*env)->CallStaticVoidMethod(env, cl, mid); 
  10.     } 

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

  1. ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);     
  2. 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:

  1. <uses-permissionandroid:name="android.permission.RESTART_PACKAGES"/> 

More detailed explanation is as follows:

  1. void android.app.ActivityManager.restartPackage(String packageName) 
  2.  
  3. 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. 
  4.  
  5. You must hold the permission android.Manifest.permission.RESTART_PACKAGES to be able to call this method. 
  6.  
  7. Parameters: 
  8.     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:

  1. publicvoid killBackgroundProcesses (String packageName) 

The api documentation is clear:

  1. public void restartPackage (String packageName) 
  2.  
  3. Since: API Level 3 
  4. This method is deprecated. 
  5. 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:

  1. <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:

  1. int currentVersion = android.os.Build.VERSION.SDK_INT; 
  2.            if (currentVersion > android.os.Build.VERSION_CODES.ECLAIR_MR1) { 
  3.                 Intent startMain =new Intent(Intent.ACTION_MAIN); 
  4.                 startMain.addCategory(Intent.CATEGORY_HOME); 
  5.                 startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
  6.                 startActivity(startMain); 
  7.                 System.exit(0); 
  8.             }else {// android2.1 
  9.                 ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); 
  10.                 am.restartPackage(getPackageName()); 
  11.             } 


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:

view plain
  1. System.exit(int); 
  2. onDestroy(); 

Keywords: Android Java SDK JDK

Added by aaron_mason on Sun, 02 Jun 2019 00:00:27 +0300