SoFunction
Updated on 2025-04-10

Android physical key sorting and instance code

Let me show you a piece of code first and then explain it.

import ;
 import ;
 import ;
 import ;
 import ;
 
 public class MainActivity extends Activity {
 
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
     (savedInstanceState);
     setContentView(.activity_main);
   }
   //When we handle physical key events, the callback methods provided are onKeyUp(), onKeyDown(), and onKeyLongPress(), such as volume keys and return keys  
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_BACK){
       ("TAG", "This is listening to keyboard operations, press the Back key");
     }
     return (keyCode, event);
   }
   @Override
   public boolean onKeyUp(int keyCode, KeyEvent event) {
     if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
       ("TAG", "Volume key");
     }
     return (keyCode, event);
   }
   
   //In Activity, we can rewrite the onBackPressed() method to handle the return key, such as exiting with two key presses   // When pressing for the first time, record the event  //The second pressed event is minus the first pressed time and exits if the time is less than 2s, otherwise the current time will be assigned to the first event   long startTime;
   
   @Override
   public void onBackPressed() {
     ("TAG", "Supervisor Back Key");
     
     if(()-startTime<2000){
       ();//Release resources, this can also be completed() directly, but the call to the release of the parent class is more thorough     }else{
       //Record the current time       startTime = ();
       (this, "Press Back key again to exit", Toast.LENGTH_SHORT).show();
     }
   }
   
 }
 

Some commonly used physical keys

Power key KEYCODE_POWER

Back key KEYCODE_BACK

Menu key KEYCODE_MENU

HOME key KEYCODE_HOME

Camera key KEYCODE_CAMERA

Volume keys KEYCODE_VOLUME_UP / KEYCODE_VOLUME_DOWM

Search key KEYCODE_SEARCH

Arrow keys 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 it can help you. Thank you for your support for this site!