Search code examples
androidunit-testingkeyevent

How do you send a long press from an InstrumentationTestCase?


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.


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