也許這有點晚,但可能有助於未來的參考。
方法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