使用injectInputEvent调度软键盘IME操作

时间:2019-02-04 07:06:59

标签: android reflection ime

根据this answer,我正在尝试使用InputManager和反射调度键盘IME操作。

private void pressSearch(){
    Class[] paramTypes = new Class[2];
    paramTypes[0] = InputEvent.class;
    paramTypes[1] = Integer.TYPE;

    Object[] params = new Object[2];
    params[0] = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SEARCH);
    params[1] = 0;//INJECT_INPUT_EVENT_MODE_ASYNC

    try {
        Method hiddenMethod = inputManager.getClass().getMethod("injectInputEvent", paramTypes);
        hiddenMethod.invoke(inputManager, params);
    } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        e.printStackTrace();
    }


    params[0] = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SEARCH);
    params[1] = 0;//INJECT_INPUT_EVENT_MODE_ASYNC

    try {
        Method hiddenMethod = inputManager.getClass().getMethod("injectInputEvent", paramTypes);
        hiddenMethod.invoke(inputManager, params);
    } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        e.printStackTrace();
    }

}

使用它时,出现此错误:

W/InputDispatcher: Asynchronous input event injection failed.
I/InputDispatcher: Dropped event because it is stale.

0 个答案:

没有答案