Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Generate Key Presses Programmatically Android

Tags:

java

android

key

In my application when the user presses DPAD_LEFT, i want to generate two DPAD_UP presses. I know it can be done using a method like this:

@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));

}

But, to being able to use "getCurrentInputConnection()" method, i need to extend InputMethodService and it is impossible cause my application already extends another class. Is there another way to solve this?

like image 869
sjor Avatar asked Feb 11 '11 09:02

sjor


1 Answers

Create another class which is extending InputMethodService and call it from your application.

like image 200
Vladimir Ivanov Avatar answered Nov 15 '22 00:11

Vladimir Ivanov