Exit the Android Application

Source: Internet
Author: User
Tags exit in

1. Finish () method

This method can end the current activity, but if your app has many activities, it seems a little too slow to use this method.
In addition, there is also a method finishactivity (INT requestcode). For this method, first look at the sdk api description!

Public void finishactivity (INT requestcode)
Since: API Level 1

Force finish another activity that you had previusly 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.


As you may understand, activity1 starts activity2 by startactivityforresult (intent, INT,
In activity2, activity1 is terminated by using the finishactivity (INT requestcode) method, but it is not lucky. If you don't believe it, you can demo it!

As mentioned in the above document, this method forces the activity started by startactivityforresult (intent, INT) to be disabled,
That is to say, the onactivityresult (INT requestcode, int resultcode, intent data) method in activity1 receives the result returned by activity2,
You must call finishactivity (INT requestcode) in activity1 to end activity2.
(Generally, the onactivityresult method calls this method to end activity2 ).

Force finish another activity that you had previusly started with startactivityforresult (intent, INT ).

Also, you can refer to the document and source code for the following two methods.
Finishactivityfromchild (activity child, int requestcode)
Finishfromchild (activity child)

2. killprocess

End the app by calling the Android. OS. process method, for example:
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 exit (INT code) method of Java can exit the program. by viewing the source code of this method, we know that it actually calls 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); // exit the app normally
}
});
Next, we will study this method. This method of Java. Lang. system class JDK description:
Exit
Public static void exit (INT status)

Terminate the currently running Java virtual machine. The parameter is used as the status code. By convention, a non-0 Status Code indicates that an exception is terminated.
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:
Securityexception-if the security manager exists and its checkexit method cannot exit in the specified state.
For more information, see:
Runtime. Exit (INT)
That is to say, if the parameter is not 0, the program exits unexpectedly. If the parameter is 0, the system Exits normally.
Check the source code of this method for the runtime class:


Public void 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 VM close sequence. This method never returns normally. A variable can be used as a status code. A non-zero status code indicates an abnormal termination.
The VM close sequence contains two phases. In the first phase, all registered close hooks (hooks) (if any) are started in an unspecified order and are allowed to run simultaneously until the end.
In the second stage, if exit termination is enabled, all uncalled termination methods are run. Once this phase is completed, the virtual machine will be paused.
If you call this method only after the VM has started its closing sequence, if you are running the closing Hook, the method will be blocked indefinitely.
If you have run the close hook and enabled the on-exit finalization function, This method uses the given status code (if the status code is a non-zero value) to suspend the VM;
Otherwise, the VM will be blocked indefinitely.

The system. Exit method is a traditional and convenient method to call this method.

Parameters:
Status-termination status. By convention, the non-zero status code table indicates that the operation is terminated abnormally.
Throw:
Securityexception-if the security manager exists and its checkexit method does not allow a specified status

For more information, see:
Securityexception, securitymanager. checkexit (INT), addshutdownhook (Java. Lang. Thread ),
Removeshudownhook (Java. Lang. Thread), runfinalizersonexit (Boolean), halt (INT)

This method also calls the exit () method of the shutdown class.


Static void 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:
Jniexport void 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 system. Exit () parameter returns the exit reason to the system. Generally, it can be any integer.

0 indicates normal exit, and 1 indicates abnormal.
Finally, let's talk about the difference between the finish () and exit methods:
Finish () is a class method of activity. It only applies to activity. When finish () is called, the activity is pushed to the background, and the memory is not released immediately, and the activity resources are not cleared; when system. exit (0), exit the current activity and release the resource (memory). However, this method cannot end the entire app. If there are multiple activty or other components, the service will not end.
In fact, the android mechanism determines that users cannot completely exit the application. When your application has not been used for the longest time, Android decides to disable the application.

4. restartpackage Method

Activitymanager manager = (activitymanager) getsystemservice (context. activity_service );
Manager. restartpackage (getpackagename ());

First, create the activitymanager object and call the restartpackage () method (if you are interested, you can refer to the source code ).
Note: getpackagename obtains the name of the current application package, for example, Mark. Zhang.
To exit the app in this way, you need the following permissions:


<Uses-Permission Android: Name = "android. Permission. restart_packages"/>


Detailed descriptions are 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,
Events 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.

It can be seen that processes with the same uid will be killed, related services will be stopped, all activities will be removed, and a broadcast will be sent.

Note: After android2.2, this method cannot end the application. You need to use the following method of the activitymanager class:
Public void killbackgroundprocesses (string packagename)
The API documentation clearly states:
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, you must use the following permissions:


<Uses-Permission Android: Name = "android. Permission. kill_background_processes"/>


But no matter how hard you are, You still cannot exit the app! Here is 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 details about Android. OS. Build. version. sdk_int, refer
Http://blog.csdn.net/androidbluetooth/article/details/6778422

5. Summary

Finish (): ends the current activity and the memory will not be released immediately. Follows the android memory management mechanism.

Exit (): ends the current component, such as activity, and immediately releases the resources occupied by the current activity.

Killprocess (): ends the current component, such as activity, and immediately releases the resources occupied by the current activity.

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

Note:
Except for the finish () method, you can call the life cycle methods of the activity, such as onstop () and ondestroy (). The other three exit methods do not call the life cycle methods of the activity. Unless you call the lifecycle methods of an activity before or after calling these methods. For example:
System. Exit (INT );
Ondestroy ();

Project Experience:
Actiivty A, B, and a start B, click back in B, and then return to A. The miserable scene happened. When a is returned to a, a disappears ......, and the ondestroy method of a is not called.
Think twice about it. Calm down. Since you click back, the ondestroy method of B will be called. So we can see the source of the cup:

@ Override
Protected void ondestroy (){
Super. ondestroy ();
Android. OS. process. killprocess (Android. OS. process. mypid ());
}


The culprit is Android. OS. process. killprocess (Android. OS. process. mypid () is the code that kill the process of the app. Therefore, a cannot be reproduced and the ondestroy method of a is not called.

 

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.