how to spoof arrow keys to my activity on android

前端 未结 1 1579
星月不相逢
星月不相逢 2021-01-16 00:47

I am trying to override the volume buttons to act as Up/Down arrow keys (i.e. they should move focus around on all of my activities focus-able Views.)

To do so I am

相关标签:
1条回答
  • 2021-01-16 01:39

    I figured out eventually that you need to use the Instrumentation class to send the key events, and you have to do it off of the main thread for some reason. Here are the snippets that will send down and up:

    new Thread(new Runnable() {         
       @Override
       public void run() {                 
           new Instrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
       }   
    }).start();
    
    new Thread(new Runnable() {         
       @Override
       public void run() {                 
           new Instrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_UP);
       }   
    }).start();
    

    If you use these insdie the overridden dispatchKeyEvent from the question it will correctly move focus around.

    0 讨论(0)
提交回复
热议问题