Let's look at a piece of code and then explain.
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.util.Log;
Import android.view.KeyEvent;
Import Android.widget.Toast;
public class Mainactivity extends activity {@Override protected void onCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main); //We are dealing with physical key events, the callback methods provided are onkeyup (), OnKeyDown (), and onkeylongpress (), such as volume keys, return keys @Override public boolean onKeyDown (in
T KeyCode, KeyEvent event) {if (keycode = = Keyevent.keycode_back) {log.e ("TAG", "This is the monitor keyboard operation, press the back Key");
Return Super.onkeydown (KeyCode, event);
@Override public boolean onKeyUp (int keycode, keyevent event) {if (keycode = = keyevent.keycode_volume_up) {
LOG.E ("TAG", "Volume add Key");
Return Super.onkeyup (KeyCode, event);
In//activity, we can rewrite the onbackpressed () method to handle the return key, such as two times the key to exit///First press, record Event//second pressed event minus the first pressed time less than 2s to exit, otherwise the current time will be assigned to the first event
Long StartTime; @OvErride public void onbackpressed () {LOG.E ("TAG", "Monitor back Key"); if (System.currenttimemillis ()-starttime<2000) {super.onbackpressed ()//Releasing resources, this can also be directly finish (), but the invocation of the parent class's release is more thorough}e
lse{//Record current time StartTime = System.currenttimemillis ();
Toast.maketext (This, "press the back key again", Toast.length_short). Show ();
}
}
}
Some common physical buttons
Power Key Keycode_power
Back Key Keycode_back
Menu Key Keycode_menu
Home Key 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 keys Keycode_0...keycode_9
Keycode_a ..... Keycode_z
Thank you for reading, I hope to help you, thank you for your support for this site!