Android exit application in the most elegant way (improved version) _android

Source: Internet
Author: User
Tags exit in

Let's take a look at some of the common exit methods (not elegant way)

First, the container-type

Create a global container, store all the activity, and loop through the finish when exiting

Import java.util.ArrayList;

Import java.util.List;
Import android.app.Activity;

Import Android.os.Bundle; public class Baseactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) {super.
    OnCreate (savedinstancestate);
  Add activity to Stack atycontainer.getinstance (). addactivity (this);
    } @Override protected void OnDestroy () {Super.ondestroy ();
  End activity& Remove the activity from the stack atycontainer.getinstance (). removeactivity (this);
  } class Atycontainer {private Atycontainer () {} private static Atycontainer instance = new Atycontainer ();

  private static list<activity> Activitystack = new arraylist<activity> ();
  public static Atycontainer getinstance () {return instance;
  public void addactivity (activity aty) {activitystack.add (aty);
  public void removeactivity (activity aty) {activitystack.remove (aty);
   /** * End all activity/public void finishallactivity () { for (int i = 0, size = activitystack.size (); i < size; i++) {if (null!= activitystack.get (i)) {Activi
      Tystack.get (i). Finish ();
  } activitystack.clear ();

 }

}

This approach is simpler, but you can see that Activitystack holds a strong reference to the activity, which means that when an activity exits unexpectedly, Activitystack does not even release the reference, causing a memory problem, and then we look at a similar way , but a little bit more elegant.

Second, broadcast-type

By registering a broadcast in baseactivity, sending a broadcast when exiting, finish exiting

public class Baseactivity extends activity {

  private static final String exitaction = "Action.exit";

  Private Exitreceiver Exitreceiver = new Exitreceiver ();

  @Override
  protected void onCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate);
    Intentfilter filter = new Intentfilter ();
    Filter.addaction (exitaction);
    Registerreceiver (exitreceiver, filter);

  @Override
  protected void OnDestroy () {
    Super.ondestroy ();
    Unregisterreceiver (Exitreceiver);
  }

  Class Exitreceiver extends Broadcastreceiver {

    @Override public
    void OnReceive (context context, Intent Intent ) {
      BaseActivity.this.finish ();}}}



Third, the process-type

End the application by directly killing the current application process, simple and brutal, and (WU) effective!

  Android.os.Process.killProcess (Android.os.Process.myPid ());
  System.exit (0);

  Activitymanager manager = (Activitymanager) getsystemservice (activity_service);
  Manager.killbackgroundprocesses (Getpackagename ());

These three can achieve the same effect, but in the simulator will pop unfortunately, XXX has stopped message box, but it can quit the application. Part of the real machine directly, can only finish the current activity (such as my hand on this millet note, some of the domestic ROM FW layer changes too much, use this method should be prudent).
Four, RS elegant style

What is RS type? namely Receiver+singletask. We know that the activity has four load modes, and Singletask is one of them, after using this pattern, when startactivity, it will first query the current stack for instances of activity, if it exists, then as the top of the stack, and remove the stack from all the activity on it. We open an app, first a splash page, and then finish off the splash page. Jump to the home page. Then will be on the homepage of the n jump, the period will produce a number of volatile activity, some were destroyed, and some reside in the stack, but the bottom of the stack is always our homeactivity. This makes the problem much simpler. We only need two steps to gracefully implement the app exit.

1, in the Homeactivity register an exit broadcast, and the second broadcast type, but here only need to homeactivity a page registration can.

2, set the starting mode of homeactivity for Singletask.
When we need to exit only need StartActivity (This,homeactivity,class), and then send an exit broadcast. The above code first removes all the activity above the homeactivity in the stack, and then receives the broadcast to finish itself. All OK! No frame, no need to consider the model ROM fit. There is no memory problem, it is so elegant, simple!

Five, Singletask revision style

And some of the boys after the exchange, many small partners said registered broadcast slightly trouble, in the downstairs of the small partners put forward a simpler way, the idea is very simple,
1, set the mainactivity load mode for Singletask
2, rewrite the Onnewintent method in Mainactivity
3, need to exit in the intent to add the exit tag
Because many small partners to the source of the demand is more fervent, we are here directly in the form of code to explain this way
The first step is to set the mainactivity load mode to Singletask

Android:launchmode= "Singletask"

The second step overrides the Onnewintent () method

 private static final String Tag_exit = "EXIT";

  @Override
  protected void onnewintent (Intent Intent) {
    super.onnewintent (Intent);
    if (intent!= null) {
      Boolean isexit = Intent.getbooleanextra (Tag_exit, false);
      if (isexit) {
        this.finish ();}}}
  

Step three exit

Intent Intent = new Intent (this,mainactivity.class);
    Intent.putextra (Mainactivity.tag_exit, true);
    StartActivity (Intent);

Six, lazy person type
This approach is simpler and requires only two steps

    • 1, set the mainactivity to Singletask
    • 2, will exit the export place in mainactivity

We can see that a lot of applications are double-clicked two times home key to exit the application, is based on this way to achieve, here in the paste how to handle two consecutive clicks to exit the source code

Private Boolean misexit;
@Override
  /**
   * Double-click the return key
  to exit/public boolean onKeyDown (int keycode, keyevent event) {

    if (keycode = = Keyevent.keycode_back) {
      if (misexit) {
        this.finish ();

      } else {
        toast.maketext (this, "Press Exit Again", Toast.length_short). Show ();
        Misexit = true;
        New Handler (). postdelayed (New Runnable () {
          @Override public
          void Run () {
            misexit = false;
          }
        } );
      }
      return true;
    }

    Return Super.onkeydown (KeyCode, event);
  }

The above is a detailed description of the most elegant way to get out of Android, hoping to help you learn about Android.

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.