当前位置: 代码迷 >> Android >> Android4.0之后添加虚拟按键方法
  详细解决方案

Android4.0之后添加虚拟按键方法

热度:102   发布时间:2016-05-01 10:02:22.0
Android4.0以后添加虚拟按键方法

public void sendKeySync(KeyEvent event) {

??????? long downTime = event.getDownTime();
??????? long eventTime = event.getEventTime();
??????? int action = event.getAction();
??????? int code = event.getKeyCode();
??????? int repeatCount = event.getRepeatCount();
??????? int metaState = event.getMetaState();
??????? int deviceId = event.getDeviceId();
??????? int scancode = event.getScanCode();
??????? int source = event.getSource();
??????? int flags = event.getFlags();
??????? if (source == InputDevice.SOURCE_UNKNOWN) {
??????????? source = InputDevice.SOURCE_KEYBOARD;
??????? }
??????? if (eventTime == 0) {
??????????? eventTime = SystemClock.uptimeMillis();
??????? }
??????? if (downTime == 0) {
??????????? downTime = eventTime;
??????? }
??????? KeyEvent newEvent = new KeyEvent(downTime, eventTime, action, code, repeatCount, metaState,
??????????????? deviceId, scancode, flags | KeyEvent.FLAG_FROM_SYSTEM, source);
??????? InputManager.getInstance().injectInputEvent(newEvent,
??????????????? InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
??? }
?? ?
??? /**
???? * Sends an up and down key event sync to the currently focused window.
???? *?
???? * @param key The integer keycode for the event.
???? */
??? public void sendKeyDownUpSync(int key) {?????? ?
??????? sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, key));
??????? sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, key));
??? }

需要系统权限才能使用

  相关解决方案