Back key is the back button on the phone, the general software does not capture relevant information may cause your program to be switched to the background, and return to the desktop embarrassing situation, on Android there are two ways to get the button event.
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 BooleanOnKeyDown (intKeyCode, KeyEvent event) { if(KeyCode = = Keyevent.keycode_back && event.getrepeatcount () = = 0) {//if it's back, it's not duplicated.//add your own processing logicToast.maketext (testbackactivity. This, "Monitoring System Return key", Toast.length_long). Show (); return true; } return Super. OnKeyDown (KeyCode, event);}
2. Overriding the Onbackpressed method
And for Android 2.0 started a new method, for the activity can be separately get back key press event, directly rewrite the onbackpressed method, code as follows:
@Override Public void ///super.onbackpressed (); This sentence must be called off, or else to call the default back processing mode // here to handle the logic code, Note: This method is only available for 2.0 or newer SDK}
Eg: double-exit the application:
/*** Return key two hits, first click Time*/ Private LongExittime = 0; @Override Public voidonbackpressed () {//super.onbackpressed (); This sentence must be dropped, or else to call the default back processing mode//Here's the logic code, People Note: This method is only available for 2.0 or newer SDK if((System.currenttimemillis ()-Exittime) > 2000) {Toast.maketext (Getapplicationcontext (),"Press one more time to exit the program", Toast.length_short). Show (); Exittime=System.currenttimemillis (); } Else{finish (); }}
Back-key processing in Android