SoFunction
Updated on 2025-04-10

The most elegant way to exit the app on Android (improved version)

Let's first look at several common exit methods (not elegant ways)

1. Container type

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

import ;
import ;

import ;
import ;

public class BaseActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    // Add Activity to the stack    ().addActivity(this);
  }

  @Override
  protected void onDestroy() {
    ();
    // End Activity & Remove the Activity from the stack    ().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) {
    (aty);
  }

  public void removeActivity(Activity aty) {
    (aty);
  }

  /**
    * End all activities
    */
  public void finishAllActivity() {
    for (int i = 0, size = (); i < size; i++) {
      if (null != (i)) {
        (i).finish();
      }
    }
    ();
  }

}

This method is relatively simple, but you can see that activityStack holds a strong reference to this Activity. That is to say, when an Activity exits abnormally, activityStack does not release the reference, which will cause memory problems. Next, let's look at a similar method, but it will be a little more elegant.

2. Broadcast

By registering a broadcast in BaseActivity, sending a broadcast when exiting, finish exits

public class BaseActivity extends Activity {

  private static final String EXITACTION = "";

  private ExitReceiver exitReceiver = new ExitReceiver();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    IntentFilter filter = new IntentFilter();
    (EXITACTION);
    registerReceiver(exitReceiver, filter);
  }

  @Override
  protected void onDestroy() {
    ();
    unregisterReceiver(exitReceiver);
  }

  class ExitReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
      ();
    }

  }

}

III. Process

End the application by directly killing the current application process, which is simple and crude, and has (wu) effect!

  (());
  (0);

  ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
  (getPackageName());

All three can achieve the same effect, but the Unfortunately , XXX has stopped message prompt box will pop up on the simulator, but it can indeed exit the application. Some real machines fail directly, and can only finish the current activity (for example, the Xiaomi note in my hand, the fw layer of several domestic ROMs made too many changes, so you need to be careful when using this method).
4. RS elegant style

What is RS style? That is, Receiver+singleTask. We know that Activity has four loading modes, and singleTask is one of them. After using this mode, when startActivity, it will first query whether an instance of Activity exists in the current stack. If it exists, it will go to the top of the stack and remove all activities on it from the stack. We open an app, first a splash page, and then finish the splash page. Jump to home page. Then N times will be jumped on the homepage, and an uncertain number of activities will be generated during this period. Some will be destroyed and some will reside in the stack, but the bottom of the stack will always be our HomeActivity. This makes the problem much easier. We only need two steps to achieve the exit of the app.

1. Register an exit broadcast in HomeActivity, the same as the second broadcast, but here you only need to register on one page of HomeActivity.

2. Set the startup mode of HomeActivity to singleTask.
When we need to exit, we only need to startActivity(this,HomeActivity,class) and send an exit broadcast. The above code will first remove all activities on the stack from the HomeActivity on the stack, and then receive the broadcast finish itself. Everything is OK! There is no pop-up frame, so you don’t have to consider the Rom adaptation. There will be no memory problems, it is so elegant and simple!

5. SingleTask redesign

After communicating with some young men, many friends said that it was a bit troublesome to register for a radio. The friends downstairs proposed a simpler way and their ideas were also very simple.
1. Set the loading mode of MainActivity to singleTask
2. Rewrite the onNewIntent method in MainActivity
3. Add the exit tag in the Intent when it is necessary to exit
Since many friends are eager for source code, we will explain this method directly in the form of code.
first stepSet the loading mode of MainActivity to singleTask

android:launchMode="singleTask"

Step 2Rewrite the onNewIntent() method

 private static final String TAG_EXIT = "exit";

  @Override
  protected void onNewIntent(Intent intent) {
    (intent);
    if (intent != null) {
      boolean isExit = (TAG_EXIT, false);
      if (isExit) {
        ();
      }
    }
  }

Step 3quit

Intent intent = new Intent(this,);
    (MainActivity.TAG_EXIT, true);
    startActivity(intent);

6. Lazy style
This method is simpler, only the following two steps are required

  • 1. Set MainActivity to singleTask
  • 2. Place the exit exit in MainActivity

We can see that many applications use double-click twice to exit the application, which is based on this method. Here I will post the source code of how to deal with the two consecutive clicks to exit.

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) {
        ();

      } else {
        (this, "Press again to exit", Toast.LENGTH_SHORT).show();
        mIsExit = true;
        new Handler().postDelayed(new Runnable() {
          @Override
          public void run() {
            mIsExit = false;
          }
        }, 2000);
      }
      return true;
    }

    return (keyCode, event);
  }

The above is a detailed introduction to the most elegant way to exit the Android application. I hope it will be helpful to everyone's learning Android.