android--completely off-application

Source: Internet
Author: User
Tags exit in

Recently learned to do Android game development time, found that the Android exit can not completely shut down the problem, such as: A program in the new n multiple thread, so in the exit program may not completely shut down, and finally found that only with the finish () method, Sometimes do not exit completely, personal feeling still need to add in the appropriate place: system.exit (0);

1. Finish () method

This method can end the current activity, but if your app has a lot of activity, it's a little bit stretched.

In addition, there is a method finishactivity (int requestcode), about this method, first look at the SDK API description!

 Public void finishactivity (int  requestcode)  1  int).  Parameters Requestcode  This request code, they'll all be finished.  

Perhaps you will understand that Activity1 starts Activity2 by means of method Startactivityforresult (Intent, int) and then Activity2 through method finishactivity (int request Code) to end Activity1, but very unlucky, not so. Don't believe you can do a demo!

It is clear from the above document that this method forces the Activity to start by means of the method Startactivityforresult (Intent, int), that is, the (overriding) method in Activity1 onactivityresult (int Requestcode, int resultcode, Intent data) to receive the results returned by Activity2, you must call Activity1 (int finishactivity) in Requestcode to end Activit Y2. (typically called by the Onactivityresult method to end Activity2).

int ).  Parameters  

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

int Requestcode)  Finishfromchild (Activity child)  

2. killprocess

To end the App by calling the Android.os.Process method, the 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 the Java exit (int code) method can exit the program by looking at the source code of the method, knowing that it is actually called the following method:

Runtime.getruntime (). exit (code);  

The sample code is as follows:

Btn_exit.setonclicklistener (new  Button.onclicklistener () {              @Override              public void OnClick (View v) {                  system.exit (0);   normal exit app              }          );  

Next, let's look at this approach. Java.lang.System the method JDK description for this class:

Exit      Public Static The status code for void exit (int  status)  0  indicates an abnormal termination.  the method calls the Exit method in the Runtime class. The method will never return normally.    calling System.exit (n) is actually equivalent to calling:     Runtime.getruntime (). exit (n)     parameter:  - exit status.  thrown:   - If the security manager exists and its Checkexit method does not allow exit in the specified state.  See also:  Runtime.exit (int)  

That is, if the argument is a value other than 0, an exception exits the program. If the parameter is 0, the exit is normal.

Look at runtime This class of this method source code:

 Public void exit (int  status) {          = System.getsecuritymanager ();       if NULL ) {          security.checkexit (status);      }      Shutdown.exit (status);  }  

Its API description:

 Public voidExitintstatus) Terminates the currently running Java virtual machine by starting the shutdown sequence of the virtual machine. This method returns from an unhealthy.  A variable can be used as a status code; By convention, a non-zero status code indicates an abnormal termination. The shutdown sequence for a virtual machine consists of two stages. In the first phase, all registered closing hooks (hooks), if any, are started in an unspecified order, and they are allowed to run at the same time until the end. In the second phase, if exit finalization is enabled, all the non-invoked finalization methods are run.    Once this phase is complete, the virtual machine is paused. If this method is called after the virtual machine has started its shutdown sequence, this method will be blocked indefinitely if the closing hook is running. If the close hook has been run and the exit termination is enabled ( on-exit Finalization), this method pauses the virtual machine with the given status code (if the status code is a non-0 value), otherwise it will block the virtual machine indefinitely.    The System.exit method is a traditional and convenient way to call this method. Parameters: Status-The terminating state.  By convention, a non-zero status code indicates an abnormal termination. Thrown: 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 is also called the exit () method of the Shutdown class.

Static voidExitintstatus) {Boolean runmorefinalizers=false; Synchronized (Lock) {          if(Status! =0) Runfinalizersonexit =false; Switch(state) { CaseRUNNING:/*Initiate shutdown*/ State=HOOKS;  Break;  CaseHOOKS:/*Stall and Halt*/           Break;  Casefinalizers: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 * This attempts to initiate shutdown to stall Indefinitely*/sequence ();      Halt (status); }      }  

where Runallfinalizers () is a local method:

Jniexportvoidjnicall 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 exit reason to the system, which can generally be any integer.
0 indicates normal exit, 1 indicates abnormal.

Finally, let's talk about the difference between the finish () and Exit methods:

Finish () is the activity's class method, only for activity, when the call to finish (), only the activity is pushed back to the background, and does not immediately release memory, the active resource is not cleaned; when calling System.exit (0), the Exits the current activity and frees up resources (memory), but the method does not end the entire app if there are multiple activty or other component service.

In fact, the Android mechanism determines that the user can not completely exit the application, when your application is not used for the longest time, Android itself will decide to shut down the application.

4. Restartpackage Method

Activitymanager manager = (activitymanager) Getsystemservice (context.activity_service);      Manager.restartpackage (Getpackagename ());  

You first need to create a Activitymanager object and then call the Restartpackage () method (you can see the source if you are interested).

Note: Getpackagename gets the current app package name, such as Mark.zhang

Using this method to exit the app requires permission:

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

A more detailed description, as follows:

void android.app.ActivityManager.restartPackage (String packagename)    The system perform a force stop of everything associated with the given application package. All processes this share its UID would be killed, all services it had running stopped, all activities removed, etc. In addition, a intent.action_package_restarted broadcast'll be sent, so the any of its registered alarms can be stopped , notifications removed, etc.      This method.    Parameters:      packagename The name   of the package to be stopped.

As you can see, the process of the same UID is killed, the associated service is stopped, all the activity is removed, and a broadcast is sent.

Note A problem: After android2.2, the method can not end the application, you need to use the following method of the Activitymanager class:

 Public void killbackgroundprocesses (String packagename)  

The API documentation says clearly:

 Public void restartpackage (String packagename)     3 is deprecated .        is  for  is  Break other applications by removing their alarms, stopping their services, etc.  

In addition, you need to use permissions:

<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES"/>  

But no matter how you toss, still can't quit app, alas! Here's a way to do this:

intCurrentVersion =Android.os.Build.VERSION.SDK_INT; if(CurrentVersion >Android.os.Build.VERSION_CODES. ECLAIR_MR1) {Intent Startmain=NewIntent (Intent.action_main);                  Startmain.addcategory (Intent.category_home);                  Startmain.setflags (Intent.flag_activity_new_task);                  StartActivity (Startmain); System.exit (0); } Else{//android2.1Activitymanager 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 (): Ends the current activity and does not immediately release memory. Follow the Android memory management mechanism.

Exit (): Ends the current component, such as activity, and immediately releases the current activity's resources.

KillProcess (): Ends the current component, such as activity, and immediately releases the current activity's resources.

Restartpackage (): End the entire app, including other activity components such as service.

Special attention : Except that the finish () method can invoke the activity's life cycle method such as OnStop (), OnDestroy (), the remaining three exit apps will not invoke the activity's lifecycle method. Unless, before or after invoking these methods, the activity's life cycle method is invoked proactively. such as:

System.exit (int);  OnDestroy ();  

android--completely off-application

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.