2

Possible Duplicate:
is there a default back key(on device) listener in android?

How can I respond to the physical back button in my Android application? Like a listener of a sort.

I want to do things when that button is pressed!

Community
  • 1
  • 1
Florian Mac Langlade
  • 1,863
  • 7
  • 28
  • 57

2 Answers2

8

If I understand your question, simply override onBackPressed() in your Activity for API 5+.

@Override
public void onBackPressed() {
    super.onBackPressed();
    // Do something
}
Sam
  • 86,580
  • 20
  • 181
  • 179
  • 1
    While this technically overrides the back button, it doesn't change the default functionality. You need to control when super.onBackPressed() is called or not called to stifle or allow default handling. – Error 454 Oct 22 '12 at 18:54
  • Sorry my ignorance @Error454 I'm new to Java and Android, if I want the back button to do my own action and not the default action I can simply omit `super.onBackPressed()`, right? – Cliff Burton Aug 04 '16 at 11:05
2

You can use the following code:

@Override
public boolean onKeyDown( int keyCode, KeyEvent event )  {
    if ( keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 ) {
        // do something on back.
        return true;
    }

    return super.onKeyDown( keyCode, event );
}

You can find more information on the Android Developer's Blog.

Khantahr
  • 8,156
  • 4
  • 37
  • 60