如何以编程方式生成按键Android

sjo*_*jor 5 java android key

在我的应用程序中,当用户按下DPAD_LEFT时,我想生成两个DPAD_UP按下.我知道可以使用这样的方法完成:

@Override private boolean onKeyDown(int keyCode, KeyEvent event) {

   if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {

        keyDownUp(KeyEvent.KEYCODE_DPAD_UP);

        keyDownUp(KeyEvent.KEYCODE_DPAD_UP);

        return true;

   }
   return super.onKeyDown(keyCode,event);
}

private void keyDownUp(int a) {

        getCurrentInputConnection().sendKeyEvent(

                new KeyEvent(KeyEvent.ACTION_DOWN, a));

        getCurrentInputConnection().sendKeyEvent(

                new KeyEvent(KeyEvent.ACTION_UP, a));

}
Run Code Online (Sandbox Code Playgroud)

但是,为了能够使用"getCurrentInputConnection()"方法,我需要扩展InputMethodService,这是不可能的,因为我的应用程序已经扩展了另一个类.还有另一种解决方法吗?

Vla*_*nov 6

创建另一个扩展InputMethodService的类,并从您的应用程序中调用它.