也许这有点晚,但可能有助于未来的参考。
方法1:使用的仪器对象
Instrumentation instrumentation = new Instrumentation();
instrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
instrumentation.sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
方法2:使用内部API与反射
此方法使用反射来访问内部API。
private void injectInputEvent(KeyEvent event) {
try {
getInjectInputEvent().invoke(getInputManager(), event, 2);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
e.printStackTrace();
}
}
private static Method getInjectInputEvent() throws NoSuchMethodException {
Class<InputManager> cl = InputManager.class;
Method method = cl.getDeclaredMethod("injectInputEvent", InputEvent.class, int.class);
method.setAccessible(true);
return method;
}
private static InputManager getInputManager() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Class<InputManager> cl = InputManager.class;
Method method = cl.getDeclaredMethod("getInstance");
method.setAccessible(true);
return (InputManager) method.invoke(cl);
}
injectInputEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
injectInputEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
请注意:方法1是基于公共API一个干净的解决方案,并在内部,它使用从方法2相同的调用。
另请注意,这两种方法都不能从MainThread调用。
“注入触摸事件的服务”不起作用。只有系统可以做到这一点。请参阅http://stackoverflow.com/questions/5635486/android-keyevent-injection-requires-system-permissions它是关于关键事件,但触摸相同 – zapl