以编程方式发送长按键事件

时间:2018-01-15 13:49:26

标签: android

对于我的测试应用程序,我需要发送长按键事件。我正在使用以下代码。

Instrumentation mInstrumentation = new Instrumentation();
KeyEvent k = new KeyEvent(KeyEvent.ACTION_DOWN, keyEvent);
mInstrumentation.sendKeySync(k);
try {
    Thread.sleep(KEYEVENT_INTERVAL);
} catch (InterruptedException e) {}

for (int repetition = 0; repetition < times; repetition++) {
    KeyEvent newEvent = KeyEvent.changeTimeRepeat(k, SystemClock.uptimeMillis(), 1,
                                          k.getFlags() | KeyEvent.FLAG_LONG_PRESS);
    mInstrumentation.sendKeySync(newEvent);
    try {
        Thread.sleep(KEYEVENT_INTERVAL);
    } catch (InterruptedException e) {}
}

mInstrumentation.sendKeySync(
    new KeyEvent(KeyEvent.ACTION_UP, keyEvent));

但这提供了与

相同的结果
for (int i = 0; i < times; i++) {
mInstrumentation.sendKeyDownUpSync(keyEvent);
SystemClock.sleep(KEYEVENT_INTERVAL);
}

上述解决方案有何区别?

如果上述长按解决方案错误,那么如何以编程方式发送长按键事件?

0 个答案:

没有答案