Question

In Android, how can I send a long press from an InstrumentationTestCase? I'd like for instance to do a sendKeys(KEYCODE_DPAD_CENTER) but make that a long click.

Was it helpful?

Solution

Don't know if this is the only/proper way, but I managed to do it this way:

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));
}

OTHER TIPS

You could try 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 example of usage:

longPress(KeyEvent.KEYCODE_ENTER);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top