Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing Enter key on Android's onKeyDown

I'm making a remote app that requires a keyboard. I'm not using an EditText, I am forcing it to invoke pragmatically.

In the activity, I have a semi intelligent onKeyDown code that translates the android keycode into the ascii code processable by my server and sends it:

@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) {
    int asciiKey = -1;
    if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) {
        asciiKey = keyCode - KeyEvent.KEYCODE_A + 'A';
    } else if (keyCode==KeyEvent.KEYCODE_DEL) {
        asciiKey = 8;
    } else if (keyCode==KeyEvent.KEYCODE_ENTER) {
        asciiKey = 13;
    } else {
        asciiKey = event.getUnicodeChar(event.getMetaState());
    }
    out.println("k "+asciiKey);
    return super.onKeyDown(keyCode, event);
}

But when I press the Enter key, it's not sending (I've tried the Jelly Bean Default and Hacker's Keyboard). Not even a "-1". The method isn't even being called. It works for most other keys (Numbers, Letters, Backspace, Some Symbols) so it's not the app itself.

The code that invokes the keyboard and hides it later:

InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

Is there something I'm missing? Also, is there a better way to translate Android keycodes into Ascii keys (specifically replicatable by java.awt.Robot).

Thanks for any help in advance.

like image 542
Osmium USA Avatar asked Nov 03 '22 17:11

Osmium USA


1 Answers

Use this function to capture the enter key too.

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    try
    {
        //
        if(event.getAction()== KeyEvent.ACTION_UP)
        {
            System.out.println(event.getAction() + " " + event.getKeyCode() + " - " + (char) event.getUnicodeChar());
        }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

    return true;
} 
like image 180
Tihomir Tashev Avatar answered Nov 13 '22 01:11

Tihomir Tashev