android代码实现短按 长按

void sendTap(int displayId, float x, float y) {
        final long now = SystemClock.uptimeMillis();
        injectMotionEvent(InputDevice.SOURCE_TOUCHSCREEN, MotionEvent.ACTION_DOWN, now, now, x, y, 1.0f,
                displayId);
        injectMotionEvent(InputDevice.SOURCE_TOUCHSCREEN, MotionEvent.ACTION_UP, now, now, x, y, 0.0f, displayId);
    }
void sendLongTouch(int displayId, float x, float y) {
    int duration = 1000;
    final long down = SystemClock.uptimeMillis();
    injectMotionEvent(InputDevice.SOURCE_TOUCHSCREEN, MotionEvent.ACTION_DOWN, down, down, x, y, 1.0f,
            displayId);
    long now = SystemClock.uptimeMillis();
    final long endTime = down + duration;
    while (now < endTime) {
        final long elapsedTime = now - down;
        final float alpha = (float) elapsedTime / duration;
        injectMotionEvent(InputDevice.SOURCE_TOUCHSCREEN, MotionEvent.ACTION_MOVE, down, now,
                lerp(x, x, alpha), lerp(y, y, alpha), 1.0f, displayId);
        now = SystemClock.uptimeMillis();
    }
    injectMotionEvent(InputDevice.SOURCE_TOUCHSCREEN, MotionEvent.ACTION_UP, down, now, x, y, 0.0f,
            displayId);
}
private static final float lerp(float a, float b, float alpha) {
    return (b - a) * alpha + a;
}

private static void injectMotionEvent(int inputSource, int action, long downTime, long when,
                                      float x, float y, float pressure, int displayId) {
    final float DEFAULT_SIZE = 1.0f;
    final int DEFAULT_META_STATE = 0;
    final float DEFAULT_PRECISION_X = 1.0f;
    final float DEFAULT_PRECISION_Y = 1.0f;
    final int DEFAULT_EDGE_FLAGS = 0;
    MotionEvent event = MotionEvent.obtain(downTime, when, action, x, y, pressure, DEFAULT_SIZE,
            DEFAULT_META_STATE, DEFAULT_PRECISION_X, DEFAULT_PRECISION_Y,
            getInputDeviceId(inputSource), DEFAULT_EDGE_FLAGS);
    event.setSource(inputSource);
    event.setDisplayId(displayId);
    InputManager.getInstance().injectInputEvent(event,
            InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH);
}

private static int getInputDeviceId(int inputSource) {
    final int DEFAULT_DEVICE_ID = 0;
    int[] devIds = InputDevice.getDeviceIds();
    for (int devId : devIds) {
        InputDevice inputDev = InputDevice.getDevice(devId);
        if (inputDev.supportsSource(inputSource)) {
            return devId;
        }
    }
    return DEFAULT_DEVICE_ID;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值