I want the users of my android app to leave my app when they press back at a certain activity. Can this be done?
-
save the state of activity in shared pref – KOTIOS Jul 25 '13 at 08:33
-
it will be better if you describe the flow of your activities – stinepike Jul 25 '13 at 08:34
-
Do you mean you want to quit the app completely and not return to the precious activity? – Scott Helme Jul 25 '13 at 08:34
-
Is there any other way for the user to go back to a previous activity or not ? If not, you could just wipe out the activity stack by adding the proper options to your intent creating the « certain activity » you are talking about. More [here](http://stackoverflow.com/questions/3473168/clear-the-entire-history-stack-and-start-a-new-activity-on-android) – Nerkatel Jul 25 '13 at 08:43
14 Answers
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);
}

- 6,433
- 9
- 48
- 93
-
1This is a horrible way, because it totally breaks the user experience. Though it is slightly less horrible than popping up a dialog when Back is pressed. – ge0rg Jul 25 '13 at 08:38
-
2It is used in well known apps and people like it, it's a lot less binding than a pop up (yes/no) and gives the user a simple choice – An-droid Jul 25 '13 at 08:41
-
2Yes, unfortunately. Many apps on Android have broken UX, but there is no reason to encourage people to continue doing so. Regarding the choice - the user already chose to leave the current activity when they pushed back. There is no need to confuse them. – ge0rg Jul 25 '13 at 08:46
-
2I don't think we can talk about "broken UX" here. Giving the user a simple information about what he is about to do can have it's use depending on the situation. – An-droid Jul 25 '13 at 08:53
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.

- 3,274
- 4
- 25
- 39
-
Would this not simply return him to the previous activity like the back button? http://developer.android.com/reference/android/app/Activity.html#finish() – Scott Helme Jul 25 '13 at 08:39
You Can Try this one
public void onBackPressed() {
moveTaskToBack(true);
}

- 3,886
- 8
- 33
- 66
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();
}
}

- 8,594
- 10
- 39
- 63

- 7,404
- 3
- 29
- 44
Updated Answer
This will finish the app:
finishAffinity();
This will kill the app and releases the resources (abruptly and without any animation):
System.exit(0);
Old Answer:
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

- 1,044
- 10
- 11
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

- 979
- 9
- 16
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);
}

- 6,383
- 7
- 46
- 68
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.

- 4,786
- 2
- 23
- 35
-
There are times when you don't want to return to the previous activity screen, like returning to the login screen from the home screen or returning to a splash screen. – Ojonugwa Jude Ochalifu May 03 '15 at 17:07
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);
I use this method to leave an app on Back press:
@Override
public void onBackPressed() {
enter code here
finish();
}

- 36
- 3
You can use moveTaskToBack() in the onBackPressed() method to exit app.
@Override
public void onBackPressed() {
moveTaskToBack(true);
}

- 34,072
- 23
- 111
- 129

- 133
- 7
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);
}

- 4,121
- 5
- 38
- 62
@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();
}

- 187
- 1
- 4
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);
}

- 18,610
- 7
- 91
- 99