How to provide input to a webView input field programmatically in Android Kitkat (4.4)

android, dispatch, input, key, webview

Solution

You can use the `Instrumentation` class for this. I've tested it with Android 4.4 and it works.

First ensure that the `WebView` has focus, then call `sendCharacterSync()` to send individual key events. Note that these calls must be done from a background thread (this is mandatory).

For example:

final Instrumentation instrumentation = new Instrumentation();

new Thread(new Runnable()
{
    @Override
    public void run()
    {
        instrumentation.sendCharacterSync(KeyEvent.KEYCODE_H);
        instrumentation.sendCharacterSync(KeyEvent.KEYCODE_I);
        instrumentation.sendCharacterSync(KeyEvent.KEYCODE_TAB);
        instrumentation.sendCharacterSync(KeyEvent.KEYCODE_T);
        instrumentation.sendCharacterSync(KeyEvent.KEYCODE_H);
        instrumentation.sendCharacterSync(KeyEvent.KEYCODE_E);
        instrumentation.sendCharacterSync(KeyEvent.KEYCODE_R);
        instrumentation.sendCharacterSync(KeyEvent.KEYCODE_E);
    }
}).start();

The only issue is that you get a "typewriter" effect (i.e. the letters appear one by one, not all at once).

Problem

I need to provide input to a webview input control programmatically. For that I was using webView.dispatchKeyEvent() and it worked fine till Android 4.3 version but it is not working in 4.4 version (Kitkat - Chromium webView). I see the below statements in the logcat: ``` W/UnimplementedWebViewApi(9737): Unimplemented WebView method onKeyMultiple called from: android.webkit.WebView.onKeyMultiple(WebView.java:2179) ``` I have tried dispatchKeyEvent(), onKeyDown() but nothing is working for Chromium webView in 4.4, please can someone let me know if there is a way to send input to webView fields programmatically. Please note that I am looking for a generic solution for any webpage (Eg: username and password fields in Facebook URL) where I don't know the name/id of the input control so cant use a simple Javascript method for loading input.

Original source