How to catch event with hardware back button on android ? I need to supress user to go back and I when click on back button on phone to show message and not to go on previous activity. How to do that ?
Asked
Active
Viewed 4.5k times
3 Answers
71
you can do by this
override the onBackPressed() method into your Activity like this way
public void onBackPressed(){ // do something here and don't write super.onBackPressed() }override the onKeyDown() method
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch(keyCode){ case KeyEvent.KEYCODE_BACK: // do something here return true; } return super.onKeyDown(keyCode, event); }
Pratik
- 30,557
- 17
- 84
- 156
-
2Is it really necessary to override `onKeyDown()` too? When the back key is pressed, won't `onBackPressed()` be called? – LarsH Aug 16 '17 at 10:24
-
1@LarsH in case you are still wondering: No. The first solution is for API Level 5 (Android 2.0) and above. The second solution is for API Level < 5. Referring to [this comment/answer](https://stackoverflow.com/questions/5312334/how-to-handle-back-button-in-activity#comment5992484_5312391) – Alex Mar 05 '19 at 14:27
10
Override the method onBackPressed() in whatever Activity you want to create a different behaviour to the back button.
These question are equal to yours (and could have been found by a simple search):
Community
- 1
- 1
kaspermoerch
- 15,582
- 3
- 40
- 64
2
You can suppress user "back" action with onKeyDown() in your activity like this:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
//do actions like show message
return false;
}
return super.onKeyDown(keyCode, event);
}
Paul Roub
- 35,848
- 27
- 79
- 88
Guillermo Gonzalez
- 51
- 3