2018年12月2日 星期日

18-input三兄弟swipe

input swipe 的功能和 MonkeyDevice.drag 類似,都是模擬手指滑動螢幕的行為,其使用方式也雷同:
語法 input swipe <x1> <y1> <x2> <y2> [ duration(ms) ]
說明 功能與 MonkeyDevice.drag (tuple start, tuple end, float duration, integer steps) 類似。
duration 預設為 300 ms。

input swipe 的使用方式如下:
# 匯入所需模組
import os

# A: 手指由 (900, 900) 滑到 (400, 900),歷時 0.3 秒
os.system('adb shell input swipe 900 900 400 900')

# B: 手指由 (900, 900) 滑到 (400, 900),歷時 1 秒
os.system('adb shell input swipe 900 900 400 900 1000')

# C: 手指由 (900, 900) 滑到 (400, 900),歷時 3 秒
os.system('adb shell input swipe 900 900 400 900 3000')

看官若執行 A、B 和 C 並與 07-迷霧中的MonkeyDevice.drag 中的例子做一個對照,便會了解 input swipe 與 MonkeyDevice.drag 在執行滑動時的不同處,其中一點便體現在 duration 參數的表現上。
MonkeyDevice.drag 的 duration 參數並不代表整個方法執行的時間,其執行時間還深受 steps 參數的影響;但 input swipe 沒有 steps 這參數,所以 duration 所指派的時間與命令執行的時間大致相同,咱們可由 input 原始碼來窺見一二:
private void sendSwipe(int inputSource, float x1, float y1, float x2, float y2, int duration) {
    if (duration < 0) {
        duration = 300;
    }
    long now = SystemClock.uptimeMillis();
    injectMotionEvent(inputSource, MotionEvent.ACTION_DOWN, now, x1, y1, 1.0f);
    long startTime = now;
    long endTime = startTime + duration;
    while (now < endTime) {
        long elapsedTime = now - startTime;
        float alpha = (float) elapsedTime / duration;
        injectMotionEvent(
            inputSource,
            MotionEvent.ACTION_MOVE,
            now,
            lerp(x1, x2, alpha),
            lerp(y1, y2, alpha),
            1.0f
        );
        now = SystemClock.uptimeMillis();
    }
    injectMotionEvent(inputSource, MotionEvent.ACTION_UP, now, x2, y2, 0.0f);
}
對照 07-迷霧中的MonkeyDevice.drag 的分析,MonkeyDevice.drag 在每一次的 MotionEvent.ACTION_MOVE 之後都會睡一段時間,但 input swipe 在每次送出 MotionEvent.ACTION_MOVE 之後(第 12 行)並不會再額外等待,而是檢查是否超過 duration 所規定的時間(第 9 行),若已超過,則送出 MotionEvent.ACTION_UP(第 22 行);否則繼續送出 MotionEvent.ACTION_MOVE,所以 duration 所指派的時間大致與 input swipe 執行的時間一致。

沒有留言:

張貼留言