-1

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

3 Answers3

0

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);
}
bobby.dhillon
  • 319
  • 1
  • 6
0

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?

Community
  • 1
  • 1
pozuelog
  • 1,284
  • 13
  • 27
0

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().

Yjay
  • 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
  • am I doing right? startActivity(intent); finish(); – user3185522 Jan 15 '14 at 18:20