7

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?

Nanne
  • 64,065
  • 16
  • 119
  • 163
sjor
  • 1,438
  • 5
  • 17
  • 22

4 Answers4

7

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

Vladimir Ivanov
  • 42,730
  • 18
  • 77
  • 103
4
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
Hayden Thring
  • 1,718
  • 17
  • 25
  • 1
    I have the need to map hardware keyboard A to number 2 and I have used this by calling it from onKeyDown, since on KeyDown is called when the event is not processed and my EditText has input type number. It appears to work. – Čikić Nenad Mar 22 '17 at 05:12
3

If you want to generate a key event that gets passed through the event pipeline and is fully handled (characters as well as special keys such as arrows - resulting in change focus) you must tap into the base of things. you can create an implementation of input method service but this is laborious. An easyer way is to get the handler of the current view hierarchy and send a message to it like this:

public final static int DISPATCH_KEY_FROM_IME = 1011;

KeyEvent evt = new KeyEvent(motionEvent.getAction(), keycode);
Message msg = new Message();
msg.what = DISPATCH_KEY_FROM_IME;
msg.obj = evt;

anyViewInTheHierarchy.getHandler().sendMessage(msg);

Simple :)

takrl
  • 6,356
  • 3
  • 60
  • 69
n0sferat0k
  • 31
  • 1
0

I have not tried this (can't right now, sorry), and it does feel a bit like a hack, but couldn't you do something like this:

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

   if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
        super.onKeyDown(KeyEvent.KEYCODE_DPAD_UP,event);  
        return super.onKeyDown(KeyEvent.KEYCODE_DPAD_UP,event);  
   }
   return super.onKeyDown(keyCode,event);
}

Ofcourse, you could create another class and call that from your application.

Nanne
  • 64,065
  • 16
  • 119
  • 163