Android's Perfect Exit method

Source: Internet
Author: User

Why did you write this article?

There are many kinds of exit methods on the Internet, but in fact many methods are not universal (available in one version, not in another version), or the actual effect of the method and its description does not match (and do not know those who posted the test has not tested).

But our needs do exist. In some cases, we need to open multiple activity in the app, but if only using the finish () method can not reach the effect of a one-time exit when needed, as a victim of Android exit problem, through long thinking and practical testing, found a relatively good, The full exit method, which is generally available under the 2.1-2.2-2.3 version (version 2.1 also basically represents the 1.5~2.1 version)!

PS: Test all in simulator environment

I'll start by explaining that the following two methods work exactly the same

1,android.os.process.killprocess (Android.os.Process.myPid ()); (This is the local method of the Dalvik VM)

2,system.exit (0); (Normal Java, C # Standard Exit method, return value of 0 means normal exit)

After that, all my instructions are based on the android.os.Process.killProcess (Android.os.Process.myPid ()) method.

In addition, the entrance to the program I'm talking about is the activity that is configured in Androidmanifest.xml as the following statement

<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>

Start our Android Perfect exit tour below:

Start with a paragraph of the online description:

A->b
b in the executive Android.os.Process.killProcess (Android.os.Process.myPid ());
The result is that B is ended and a is restarted.
The reality is this: A is the program entry, B calls the KillProcess (Android.os.Process.myPid ()) operation, actually closes both the program entry A and Activity B executing the statement, and restarts the new program entry A.

So, if the process is a->b->c

The actual situation is: A is the program entry, C calls KillProcess (Android.os.Process.myPid ()) operation to the program entry A and the execution of the statement activity C is closed, and restart the new program entry a (in the Activity window history stack, the old A is closed, the new a will still be placed in the old A's stack location, will not reach the top of the stack).

PS: if KillProcess (Android.os.Process.myPid ()) or system.exit (0) is executed at the program inlet A, the entry A is closed and no new A is opened.

Someone asked, B activity? b still exists, and B activity is not closed.

How to solve this problem?

Let's start by stating

Android.os.Process.killProcess (Android.os.Process.myPid ()); After the statement executes, the code behind it will no longer execute;

and finish (), or startactivity (a.this,b.class); The statement will still execute subsequent code after execution is complete. (Use Thread.Sleep multiple verification, do not worry about the finish () after not startactivity, the opposite is the same).

So, we can take advantage of this, since finish (), and startactivity (A.this,b.class); The statement can still perform subsequent code operations after execution, so we can combine it in a code fragment, i.e.

StartActivity (New Intent (B.this, C.class));
Finish ();

Or

Finish ();

StartActivity (New Intent (B.this, C.class));

Yes, we use the code snippet in B to close the B activity and open the C activity, before the problem done!

If you still have d,e,f ... That's the same, use the finish () piece each time you jump to the next activity. In this way, the extra activity can be turned off.

Finally, let's assume we have the following requirement to summarize the above content:

Activity is turned on 1.Index----2.a_activity---4.Index, at 4. Exit is implemented in index, and index is the program entry.

IndexExit: Is the simplest finish (); Jump: Also the simplest startactivity (new Intent (Index.this, A_activity.class)); a_activityBack to the first interface: in two cases 1, need index update (my index has this demand, the first page color changes) using Android.os.Process.killProcess (Android.os.Process.myPid ()); Close yourself and the previous index, create a new index;2, do not need the new index,index without change using the simplest finish (), and the efficiency is higher. Jump: Finish ();

StartActivity (New Intent (A_activity.this, C.class));

Close itself to activate other activity other than Index.

B_activity

The operation is the same as a_activity. Of course the jump statement becomes

Finish ();

StartActivity (New Intent (B_activity.this, Index.class));

*************************************************************************************************************

The above content is this, I will tell you the other way, you can do not close the middle of the activity, but in the back of the operation to turn off all activity in the front, can meet some people by pressing the return key to return to the previous interface requirements!

Using the history stack provided by the android window class, we use the principle of stack, we add the flag intent.flag_activity_clear_top to the Intent.

Intent Intent = new Intent ();

Intent.setclass (One.this, Two.class);
Intent.setflags (Intent.flag_activity_clear_top);
StartActivity (Intent);

Suppose you have the following requirements:

1.Index--2.a_activity-3.b_activity

Set Intent.setclass (B_activity.this, Index.class) in 3;

After jumping, the program will look backwards from the top of the stack until the nearest index in the stack is found, and then close all the activity that has been found, including 1, 2, 3 (and no need to finish the way I did before, and keep the activity on the way), Finally, a new index activity is placed at the top of the stack and then exited using the Finish method in the Index window.

If not understood, look at this example:

If 3 is set in Intent.setclass (B_activity.this, A_activity.class);

is to close 2, 3, and then create a new 4. A_activity, the stack becomes

1.Index--4.a_activity, understand!

It is important to note that in the following scenario

1.Index--2.a_activity-3.b_activity-4.Index--5.a_activity

Use of Intent.setclass (A_activity.this, B_activity.class) in 5;

The result is not

1.Index--2.a_activity-6.b_activity

But

1.Index----2.a_activity----------------5.a_activity, because 4 (program entry) exists, So 5 to the stack operation will not reach 3, but found that 4, 5 have no b_activity, did not close any activity, only the top of the stack to create a new 6. B_activity.

This also indirectly shows that the Dalvik virtual machine traversal algorithm only to the nearest program entrance, it is considered that there is no activity of the program. So good Android programming habit is to create a new program at the entrance, must be the old program entrance shut down, which also explains why the KillProcess method after the update of the program entry index must still be in the old position in the stack, not to the top of the stack.

I like this method very much.

**********************************************************************************************

There is also a popular Android Classic Perfect Exit method, using Singleton mode to create an activity management object, the object has an activity container (specifically to implement their own processing, The use of LinkedList, etc.) is specifically responsible for storing the newly opened each activity, and easy to understand, easy to operate, very good!

MyApplication Class (stores each activity and implements the action to close all activity)

public class MyApplication extends application {


Private list<activity> activitylist = new linkedlist<activity> ();
private static MyApplication instance;

Private MyApplication ()
{
}
Get a unique MyApplication instance in singleton mode
public static MyApplication getinstance ()
{
if (null = = instance)
{
Instance = new MyApplication ();
}
return instance;

}
Adding activity to the container
public void addactivity (activity activity)
{
Activitylist.add (activity);
}
Traverse all activity and finish

public void exit ()
{

for (Activity activity:activitylist)
{
Activity.finish ();
}

System.exit (0);

}
}

Add the activity to the MyApplication object instance container in each activity's OnCreate method

Myapplication.getinstance (). addactivity (this);

Call the Exit method when you need to end all activity

Myapplication.getinstance (). exit ();

It is reported that if a program crashes, it may cause the class to be forced to shut down and rebuild so that pre-placed activity does not shut down properly.

————————————— Split Line —————————————————

Some of the other exit methods I have introduced and reviewed (please correct me):

@restartPackage (Getpackagename ()) (not in detail)

I developed under the SDK2.1 version of a small software, put on the Android2.2 or 2.3 operating system can not quit, because the Restartpackage method after SDK2.1 version has been deprecated, because it is not secure, may be closed with other applications shared service, and this SE Rvice others to use it, you have to shut the others is not right.

@ Some say the ultimate exit method:

Intent Startmain = new Intent (intent.action_main);
Startmain.addcategory (Intent.category_home);
Startmain.setflags (Intent.flag_activity_new_task);
StartActivity (Startmain);

System.exit (0);

In fact, this method simply returns to the home page, and if you go into the app again, you'll find that the first interface you've entered is the activity you didn't close previously.

The @ call system hides the Forcestoppackage method, which is called through the mapping (there are other methods)

method = null;

Activitymanager manager = (Activitymanager) getsystemservice (Activity_service);
try {
method = Class.forName ("Android.app.ActivityManager"). GetMethod ("Forcestoppackage", String.class);
Method.invoke (Manager,getpackagename ());
} catch (Exception e) {
LOG.D ("Force", E.getmessage ());

}

My test results in SDK2.2 and 2.3 were that there was a nullpointerexception, pop-up error window, the program was forced to close, and the expected normal exit was different. However, we can implement the Uncaughtexception method of our Thread.uncaughtexceptionhandler interface by modifying the base class so that there will be no error window popup. The program exits completely.

@ is the same as above, but this is deliberately to create an abnormal exit (the top is unintentionally created exception), but I think this is the worst way.

Android's Perfect Exit method

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.