Leaving android app with back button

送分小仙女□ 提交于 2019-11-30 05:13:38

You can try something like this (shows a dialog to confirm exit):

        @Override
        public void onBackPressed() {
                    new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
                            .setMessage("Are you sure you want to exit?")
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                    System.exit(0);
                                }
                            }).setNegativeButton("No", null).show();
                }

It must be noted as it is mentioned in the comments below that exiting an app with System.exit is not recommended. A more "correct" way would probably be to broadcast an intent on back pressed and if the activities of your application received that intent finish themselves.

A good way is to wait for a second back

private boolean             _doubleBackToExitPressedOnce    = false;

@Override
public void onBackPressed() {

    Log.i(TAG, "onBackPressed--");
    if (_doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }
    this._doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Press again to quit", Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            _doubleBackToExitPressedOnce = false;
        }
    }, 2000);
}

You Can Try this one

public void onBackPressed() {
    moveTaskToBack(true);
}
Bhoomika Brahmbhatt

Put it in every activity of your Manifest:

<activity android:name=".MyActivity" 
          android:noHistory="true">
</activity>

On Back press from your Activity:

@Override
protected void onBackPressed() {
    if (this.isFinishing()){ 
        finish();
        super.onBackPressed();
    }
}

I know this is an old post. But this might be helpful for someone just as it was to me, who wants to implement the same feature in their application.

The solution for identifying double back can be done by calculating the time between two back press. If the difference is less than 2seconds (i.e. 2000 milliseconds) then you can accept that as double back press and exit from the application. Otherwise display the Toast message.

Simple implementation of this would be:

private static long back_pressed;

@Override
public void onBackPressed()
{
        if (back_pressed + 2000 > System.currentTimeMillis()) 
            super.onBackPressed();
        else 
            Toast.makeText(getBaseContext(), "Press once again to exit!",Toast.LENGTH_SHORT).show();

        back_pressed = System.currentTimeMillis();
}

The code can be found in this link

You can override onBackPressed() in the activity and do whatever you want in it. Here is the code that exits the app when back is pressed:

@Override
public void onBackPressed(){
  Intent intent = new Intent(Intent.ACTION_MAIN);
  intent.addCategory(Intent.CATEGORY_HOME);
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);
}

It seems what you're asking would break the purpose of the back button and the expected flow of an application. A user would expect a press of the back button to return them to the previous activity screen.

If you want to terminate the entire application with the back button, each time you use startActivity() follow it with a call to finish(). This will close the current activity as you leave so if the user presses the back button they will leave your app.

Instead of overriding the back button behaviour consider using the FLAG_ACTIVITY_CLEAR_TOP intent flag to control the activity stack of your application.

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

For example, consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.

Using the example above. It would be implemented something like this: From the activity D:

Intent intent = new Intent(context, B.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

First of all it is completely weird that you want to close your application because normally if user leaves your app, android handles the rest of it and decides either to close or keep it paused based on memory status of the device and it does a perfect job on it, meaning you shouldn't be worried about it.

But if you want to close your app, in case there is only one activity running (at the time of pressing back button in your case) closing that activity closes the whole app. what I mean is that if you have transmitted to current activity using an intent and didn't close previous activity then using this.finish() closes just the current activity and gets you back t the previous paused activity, otherwise it closes the whole app. consider the fact that an activity may use a fragmet and fragments can be without layouts. then it seems like the app is closed while it is still running.

But how to use hardware back key to do your job? you will need to do this

@Override
public void onBackPressed()
{
    if(/* check a condition to make sure you are in that certain activity */)
    {
        Process.killProcess(Process.myPid()); 
    }
    else
    {
        super.onBackPressed();
    }
}

Good luck

I use this method to leave an app on Back press:

@Override
public void onBackPressed() {
enter code here
    finish();
}

You can achieve anything with Overriding the Back Button.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // Do whatever you want with your activity
        // And for closing the whole app, you can use System.exit() which is absolutely not recomended
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
@Override
    public void onBackPressed(){ 
         new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
         .setMessage("Are you sure you want to exit?")
         .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
             @Override
             public void onClick(DialogInterface dialog, int which) {
                 Intent intent = new Intent(Intent.ACTION_MAIN);
                  intent.addCategory(Intent.CATEGORY_HOME);
                  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                  startActivity(intent);
             }
         }).setNegativeButton("No", null).show();

    }

Here is a ready method to manage backPressed() when pressed twice at a time and call a confirmation dialog:

/**
 * Overrides Back Pressed Button handler.
 * Single continuous press custom clear in your activity.
 * Double continuous press - confirmation dialog to close all activities and exit to Android.
 */
@Override
public void onBackPressed() {

if (isBackPressedTwice) {

  new AlertDialog.Builder(this)
    .setCancelable(false)
    .setIcon(
      R.drawable.exit)
    .setTitle(
      getString(
        R.string.exit))
    .setMessage(
      getString(
        R.string.close_application))
    .setNegativeButton(
      getString(
        R.string.no),
      null)
    .setPositiveButton(
      getString(
        R.string.yes),
      new DialogInterface.OnClickListener() {
        @Override
        public void onClick(
          DialogInterface dialog,
          int which) {

          finishAffinity();

          return;
        }
      })
    .show();
} else {
  // Custom activity clearing operations.
}

this.isBackPressedTwice = true;

new Handler().postDelayed(
  new Runnable() {
    @Override
    public void run() {

      isBackPressedTwice = false;
    }
  },
  1000);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!