1 Importandroid.app.Activity;2 ImportAndroid.os.Bundle;3 ImportAndroid.util.Log;4 Importandroid.view.KeyEvent;5 ImportAndroid.widget.Toast;6 7 Public classMainactivityextendsActivity {8 9 Ten @Override One protected voidonCreate (Bundle savedinstancestate) { A Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); - } the //when we handle physical key events, we provide callback methods such as onkeyup (), OnKeyDown (), and onkeylongpress (), such as volume keys, return keys - - @Override - Public BooleanOnKeyDown (intKeyCode, KeyEvent event) { + if(KeyCode = =keyevent.keycode_back) { -LOG.E ("TAG", "This is the listening keyboard operation, press the back key"); + } A return Super. OnKeyDown (KeyCode, event); at } - @Override - Public BooleanOnKeyUp (intKeyCode, KeyEvent event) { - if(KeyCode = =keyevent.keycode_volume_up) { -LOG.E ("TAG", "Volume plus key"); - } in return Super. OnKeyUp (KeyCode, event); - } to + //in activity, we can override the Onbackpressed () method to handle the return key, such as two-time key exit - //when you press the first time, log the event the //second press event minus less than 2s for the first time to exit, otherwise assigns the current time to the first event * LongStartTime; $ Panax Notoginseng @Override - Public voidonbackpressed () { theLOG.E ("TAG", "Listen Back Key"); + A if(System.currenttimemillis ()-starttime<2000){ the Super. onbackpressed ();//Release the resource, this can also be directly finish (), but call the parent class to release more thoroughly +}Else{ - //record the current time $StartTime =System.currenttimemillis (); $Toast.maketext ( This, "Press the back key again to exit", Toast.length_short). Show (); - } - } the -}
Some common physical keys
Power Key Keycode_power
Back Key Keycode_back
Menu Key Keycode_menu
HOME Button Keycode_home
Camera Key Keycode_camera
Volume key KEYCODE_VOLUME_UP/KEYCODE_VOLUME_DOWM
Search Key Keycode_search
Directional key Keycode_dpad_center
Keycode_dpad_up
Keycode_dpad_down
Keycode_dpad_left
Keycode_dpad_right
Keyboard key Keycode_0...keycode_9
Keycode_a .... Keycode_z
Android Physical Keys