How do I trigger any keycode key events in Android's webview?

2.5k Views Asked by At

For example, what should I do if I want a web page to get an event with a keycode value of - 1?

I tried to use webview.dispatchKeyEvent(...), but if the value of KeyEvent is not in the constant defined by KeyEvent.KEYCODE_XXX, it is converted to keyEvent.KEYCODE_UNKNOWN. That is, the event keycode value received on the page is 0

What should I do?

API 19

Both Webview and Crosswalk are okay.

1

There are 1 best solutions below

0
Piotr Kosmala On

In javascript add two functions to window object: keyDown and keyUp. In java override dispatchKeyEvent function in your main activity:

@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
    final int keyCode = event.getKeyCode();
    final int keyAction = event.getAction();

    if (keyAction == KeyEvent.ACTION_DOWN)
        loadUrl("javascript:keyDown(" + keyCode + ")");
    else if (keyAction == KeyEvent.ACTION_UP)
        loadUrl("javascript:keyUp(" + keyCode + ")");

    return true;
}

Adjust this function to handle unsupported keys. The point is that once you read the key in java you can then call custom js functions without passing '0' value.

In my case I did:

@Override
public boolean dispatchKeyEvent(KeyEvent event)
{
    final int keyCode = event.getKeyCode();
    final int keyAction = event.getAction();
    final boolean keySupported = KeyHelper.isKeySupported(keyCode);

    if (keySupported)
    {
        if (keyAction == KeyEvent.ACTION_DOWN)
            loadUrl("javascript:keyDown(" + keyCode + ")");
        else if (keyAction == KeyEvent.ACTION_UP)
            loadUrl("javascript:keyUp(" + keyCode + ")");

        return true;
    }

    return super.dispatchKeyEvent(event);
}

where isKeySupported function checks a list of all the keys I want to handle.