在调试安卓代码的时候经常会用到input keyevent keycode来操作按键,确定按键功能是否正常。有时候也会在安卓应用服务里面发送按键给所有的应用或者发送坐标数据来模拟触摸,比如原车带触摸屏与机器通信,通过原车的触摸来控制机器的应用操作,这就需要在应用服务中调用接口函数来发送按键和坐标数据。
我们可以建立一个控制接口类给到应用服务调用,代码参考如下:
public class TouchController {
private static long mDownTime;
public static boolean sendKey(int keyCode, int metaState) {
final long eventTime = SystemClock.uptimeMillis();
KeyEvent downEvent = KeyEvent.obtain(eventTime, eventTime, KeyEvent.ACTION_DOWN,
keyCode, 0, metaState, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0,
InputDevice.SOURCE_KEYBOARD, null);
if (injectEventSync(downEvent)) {
KeyEvent upEvent = KeyEvent.obtain(eventTime, eventTime, KeyEvent.ACTION_UP,
keyCode, 0, metaState, KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0,
InputDevice.SOURCE_KEYBOARD, null);
if(injectEventSync(upEvent)) {
return true;
}
}
return false;
}
public static boolean touchDown(int x, int y) {
mDownTime = SystemClock.uptimeMillis();
MotionEvent event = MotionEvent.obtain(
mDownTime, mDownTime, MotionEvent.ACTION_DOWN, x, y, 0);
event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
return injectEventSync(event);
}
public static boolean touchUp(int x, int y) {
final long eventTime = SystemClock.uptimeMillis();
MotionEvent event = MotionEvent.obtain(
mDownTime, eventTime, MotionEvent.ACTION_UP, x, y, 0);
event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
mDownTime = 0;
return injectEventSync(event);
}
public static boolean touchMove(int x, int y) {
final long eventTime = SystemClock.uptimeMillis();
MotionEvent event = MotionEvent.obtain(
mDownTime, eventTime, MotionEvent.ACTION_MOVE, x, y, 0);
event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
return injectEventSync(event);
}
private static boolean injectEventSync(InputEvent event) {
return InputManager.getInstance().injectInputEvent(event,
InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
}
}
然后应用服务可以通过如下方式调用接口实现此功能:
1,控制按键:
TouchController.sendKey(KeyEvent.KEYCODE_MEDIA_PLAY, 0);
2,控制触摸:
TouchController.touchDown(touchx,touchy);
TouchController.touchMove(touchx,touchy);
TouchController.touchUp(touchx,touchy);
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。