模拟发送按键
2019-12-23 本文已影响0人
Battery_fc
概述
客户有个需求,需要系统提供一个 模拟发送按键 的接口,之前考虑过使用adb命令的方式提供,最后 是使用了 系统 InputManager.java 提供的 injectInputEvent 注入事件的方法解决了
解决方案
调用
@Override
public boolean sendInputKeyCode(int keyCode) {
long time = SystemClock.uptimeMillis();
boolean downEvent = injectKeyEvent(time,KeyEvent.ACTION_DOWN,keyCode,0);
if(downEvent){
boolean upEvent = injectKeyEvent(time,KeyEvent.ACTION_UP,keyCode,0);
if(upEvent){
return true;
}
}
return false;
}
实现
private boolean injectKeyEvent(long time, int action, int keycode, int repeat) {
//KeyEvent keyEvent = new KeyEvent(time, time, action, keycode, repeat);
boolean result =false ;
KeyEvent keyEvent = KeyEvent.obtain(time, time, action, keycode,
repeat, 0, -1, 0, 0,
InputDevice.SOURCE_KEYBOARD,null);
result = InputManager.getInstance().injectInputEvent(keyEvent,0);
keyEvent.recycle();
return result;
}