views:

1112

answers:

5

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);
+1  A: 
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK){
        //Do stuff
    }

    return super.onKeyDown(keyCode, event);
}
YaW
+4  A: 
@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
not working.... i cant print a statement on logcat itself.
Praveen Chandrasekaran
Could you edit your question to show the code your having problems with at the moment? One of us might be able to help
Jamie Keeling
just i copy and paste your code snippet in my activity class. just replace the //do somthing on back to my edit code snippet(see the question).
Praveen Chandrasekaran
fine. its working. we have to mention what activity to class. activity.this.finish(); . thats it. Thanks a lot.
Praveen Chandrasekaran
No problem, glad you got it working.
Jamie Keeling
+1  A: 

Despite onKeyDown there is a specific method in Activity class:
@Override
public void onBackPressed() {
//Do your stuff here
}

Nikolay Ivanov
This is the preferred approach for Android 2.x. However, for earlier versions of Android, you still need to use `onKeyDown()`.
CommonsWare
not working.... i cant print a statement on logcat itself. i had used both methods.
Praveen Chandrasekaran
A: 

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
A: 

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
}
NickO