39

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 ?

Damir
  • 54,277
  • 94
  • 246
  • 365
  • Possible duplicate of [Disable back button in android](http://stackoverflow.com/questions/4779954/disable-back-button-in-android) – Ricardo A. Nov 30 '16 at 19:17

3 Answers3

71

you can do by this

  1. override the onBackPressed() method into your Activity like this way

    public void onBackPressed(){
         // do something here and don't write super.onBackPressed()
    }
    
  2. 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,639
  • 18
  • 84
  • 159
  • 2
    Is 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):

how to disable back button in android

Disable back button in android

Community
  • 1
  • 1
kaspermoerch
  • 16,127
  • 4
  • 44
  • 67
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
  • 36,322
  • 27
  • 84
  • 93