19

I am having two activities A and B. when i click the button in A that will shows B. when i click the Button in B it backs to A. i had set the overridePendingTransition method after the finish() method. it works properly. but in case the current Activity is B. on that time i click the default back button in the device. it shows the right to left transition to show the Activity A.

How i can listen that Default back key on device?

EDIT:

Log.v(TAG, "back pressed");
finish();
overridePendingTransition(R.anim.slide_top_to_bottom, R.anim.hold);
Macarse
  • 91,829
  • 44
  • 175
  • 230
Praveen
  • 90,477
  • 74
  • 177
  • 219

5 Answers5

45
@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);
}

The following link is a detailed explanation on how to handle back key events, written by the Android developers themselves:

Using the back key

Jamie Keeling
  • 9,806
  • 17
  • 65
  • 102
29

For Android 2.0 and later, there is a specific method in the Activity class:

@Override  
public void onBackPressed() {
    super.onBackPressed();   
    // Do extra stuff here
}
Sam
  • 86,580
  • 20
  • 181
  • 179
Nikolay Ivanov
  • 8,897
  • 3
  • 31
  • 34
2
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK){
        //Do stuff
    }

    return super.onKeyDown(keyCode, event);
}
YaW
  • 12,132
  • 3
  • 19
  • 23
0

More info on back key stuff can be found here: http://android-developers.blogspot.com/2009/12/back-and-other-hard-keys-three-stories.html

Moss
  • 6,002
  • 1
  • 35
  • 40
0

I use this code on an activity with a media player. I needed to stop the playback when user pressed the back button but still be able to go back to previous activity.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        // do something on back.
        try{
            mp.stop(); //this line stops the player
            return super.onKeyDown(keyCode, event);//this line does the rest 
        }
        catch(IllegalStateException e){
            e.printStackTrace();
        }
        return true;
    }

    return super.onKeyDown(keyCode, event); //handles other keys
}
NickOpris
  • 509
  • 2
  • 8
  • 20