First look at the difference between onbackpressed and onkeydown.
There are two ways to get the button's events on Android
1. Direct access to the button press event, this method is compatible with Android 1.0 to Android 2.1 is also the general method, directly rewrite the activity of the OnKeyDown method, the code is as follows:
@Override
public boolean onKeyDown (int keycode, keyevent event) {
if (keycode = = Keyevent.keycode_back) {//pressed if is back and not duplicated
Toast.maketext (Ml78.this, "Back Key Test", 1). Show ();
return true;
}
Return Super.onkeydown (KeyCode, event);
}
For Android 2.0, there is a new method, for the activity can be separately get back key press event, directly rewrite the onbackpressed method, the code is as follows
@Override
public void onbackpressed () {
Here's the logic code, people Note: This method is only available for 2.0 or newer SDK
Return
}
1 now implementation to root activity press 2 This return key implementation exits
Private Static BooleanIssysexit =false; @Override Public voidonbackpressed () {//TODO auto-generated Method Stub if(!issysexit) {Issysexit=true; Densityutil.showtoast ( This, "Press again to exit"); Timer Timer=NewTimer (); Timer.schedule (NewTimerTask () {@Override Public voidrun () {//TODO auto-generated Method StubIssysexit =false; } }, 2000); }Else{finish (); } }
2 Override the Back button in root activity to respond to an event, and when the back button is pressed, the activity is retired to the background
@Override Public BooleanOnKeyDown (intKeyCode, KeyEvent event) { //TODO auto-generated Method Stub//when you press the Back button, the activity is back to the background. if(KeyCode = =keyevent.keycode_back) {Movetasktoback (true); return true; } return Super. OnKeyDown (KeyCode, event); }
Activity pressed 2 times to exit