[Turn]android App exit

Source: Internet
Author: User
Tags exit in

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)
SINCE:API Level 1

Force finish another activity so you had previously started with Startactivityforresult (Intent, int).

Parameters Requestcode

The request code of the activity that you had given to Startactivityforresult ().
If There is multiple activities started with this request code, they would all be finished.


Perhaps you will understand that Activity1 Startactivityforresult (Intent, int) starts the Activity2 by means of the method,
Then end Activity1 in Activity2 by method finishactivity (int requestcode), but not so fortunate. Don't believe you can do a demo!

It is clear from the above document that this method forces shutdown of Activity initiated by Method Startactivityforresult (Intent, int),
That is, in Activity1 (overriding) method Onactivityresult (int requestcode, int resultcode, Intent data) to receive the results returned by Activity2,
You must call finishactivity (int requestcode) in Activity1 to end the Activity2.
(typically called by the Onactivityresult method to end Activity2).

Force finish another activity so you had previously started with Startactivityforresult (Intent, int).

Also, the following two methods, you can refer to the documentation and source research.
Finishactivityfromchild (Activity child, 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);//exit the app normally
}
});
Next, let's look at this approach. Java.lang.System the method JDK description for this class:
Exit
public static void exit (int status)

Terminates the currently running Java virtual machine. The parameter is used as a status code; By convention, a status code other than 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)

Parameters:
Status-exits the state.
Thrown:
SecurityException-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) {
SecurityManager security = System.getsecuritymanager ();
if (Security! = null) {
Security.checkexit (status);
}
Shutdown.exit (status);
}


Its API description:
Exit
public void exit (int status)


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 (on-exit finalization) is enabled, this method pauses the virtual machine with the given status code (if the status code is a non-0 value);
Otherwise, the virtual machine will be blocked indefinitely.

The System.exit method is a traditional and convenient way to call this method.

Parameters:
Status-terminates the 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 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-initiate shutdown to stall indefinitely
*/
Sequence ();
Halt (status);
}
}

where 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 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 the 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), exiting the current Activity and frees 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"/>


Add detailed instructions, 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.

You must hold the permission Android. Manifest.permission.RESTART_PACKAGES to is able to call the This method.

Parameters:
PackageName the name of the 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)

SINCE:API Level 3
This method is deprecated.
This is now just a wrapper for killbackgroundprocesses (String);
The previous behavior here's no longer available to applications
Because it allows them to breaks 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:
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 (): 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:
In addition to 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 ();

Project experience:
Actiivty A, b,a start B, click Back in B, then return to a, the tragic scene happened, back to a,a actually disappeared ..., and did not call A's OnDestroy method.
Think of the solution, calm down, since click Back, then certainly will call B OnDestroy method, so, 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 ()), which will kill the app Process, so you won't see a rendition and won't call A's Onde Stroy method.

Original posts: http://blog.csdn.net/veryitman/article/details/6574940

[Turn]android App exit

Related Article

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.