How do you send a long print with InstrumentationTestCase?

In Android, how can I send a long press with InstrumentationTestCase? I would like to do, for example sendKeys(KEYCODE_DPAD_CENTER), but do it with a long click.

+3
source share
2 answers

I don't know if this is the only / correct way, but I managed to do it as follows:

public void longClickDpadCenter() throws Exception {
    getInstrumentation().sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_CENTER));
    Thread.sleep(ViewConfiguration.get(mContext).getLongPressTimeout());
    getInstrumentation().sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_CENTER));
}
+2
source

You can try using the helper method below:

private void longPress(int key) {
    long downTime = SystemClock.uptimeMillis();
    long eventTime = SystemClock.uptimeMillis();
    KeyEvent event1 = new KeyEvent(downTime, eventTime, KeyEvent.ACTION_DOWN, key, 0);
    KeyEvent event2 = new KeyEvent(downTime, eventTime, KeyEvent.ACTION_DOWN, key, 1);
    getInstrumentation().sendKeySync(event1);
    getInstrumentation().sendKeySync(event2);
}

And an example of use:

longPress(KeyEvent.KEYCODE_ENTER);
0
source

Source: https://habr.com/ru/post/1747220/


All Articles