Hello I want to make an Activity, that on clicking back it closes, in stead of going to the previous activity. Please tell me how to do it. Thank you in advance
-
1you can clear the activity back stack. but why do you want that. it is normal to go back to the previous activity – Raghunandan Jan 15 '14 at 17:22
-
in general yes, but for one place I must do so, si how to clear activity back stack? – user3185522 Jan 15 '14 at 17:25
-
1http://stackoverflow.com/questions/5794506/android-clear-the-back-stack – Raghunandan Jan 15 '14 at 17:26
3 Answers
Try putting this in your activity class:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Add you custom code here
return true;
}
return super.onKeyDown(keyCode, event);
}

- 319
- 1
- 6
You can receive press by overriding 'onBackPressed', for example:
@Override
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
}
Nevertheless, this is bad practice. You shouldn't exit app when user press back button. If user would wanted to close app... He would press home button. Maybe you should read this.. Is quitting an application frowned upon?
I strongly advise against approaching your problem as "I want to close my application when I press back", as this tends to migrate towards the evil Android anti-pattern of killing the process (as suggested in other answers).
Instead, I would focus more on the fact that you do not want previous Activities
in your application to be saved in your application's back stack. A simple way to do this is whenever you call startActivity(...)
you call finish()
immediately afterwards, removing the old Activity
from your back stack. When you press Back, the "previous" Activity
is now whatever started your application in the first place (likely the user's application launcher), and will be shown.
Alternatively, if you also want the application to close when the user navigates to a different application (such as using Recent Tasks, opening a notification, or receiving a phone call), you can add the noHistory
flag to your activities in your manifest, as follows:
<activity
...
android:noHistory="true"
...
</activity>
The noHistory
flag ensures that when the user navigates away from the Activity
, it is automatically finished, via finish()
.

- 2,717
- 1
- 18
- 11
-
Thank you very much for detailed explaining, and as I understand you want to say smth like the first answer of this question: http://stackoverflow.com/questions/5794506/android-clear-the-back-stack , but it is not working in my app I don't know why, may be because the activity what I want to override and to close is the Main Activity? – user3185522 Jan 15 '14 at 18:16
-
The MainActivity in your app is just like all of the other Activities, except that it can be opened from the launcher. What problems are you experiencing? – Yjay Jan 15 '14 at 18:18
-