JRL
JRL

Reputation: 78023

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.

Upvotes: 3

Views: 2741

Answers (3)

jintao wu
jintao wu

Reputation: 21

Line 179 in the android source code:

class InputKeyEvent implements InputCmd {
    @Override
    public void run(int inputSource, int displayId) {
        String arg = nextArgRequired();
        final boolean longpress = "--longpress".equals(arg);
        if (longpress) {
            arg = nextArgRequired();
        }

        do {
            final int keycode = KeyEvent.keyCodeFromString(arg);
            sendKeyEvent(inputSource, keycode, longpress, displayId);
        } while ((arg = nextArg()) != null);
    }

    private void sendKeyEvent(int inputSource, int keyCode, boolean longpress, int displayId) {
        final long now = SystemClock.uptimeMillis();
        int repeatCount = 0;

        KeyEvent event = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keyCode, repeatCount,
                0 /*metaState*/, KeyCharacterMap.VIRTUAL_KEYBOARD, 0 /*scancode*/, 0 /*flags*/,
                inputSource);
        event.setDisplayId(displayId);

        injectKeyEvent(event);
        if (longpress) {
            repeatCount++;
            injectKeyEvent(KeyEvent.changeTimeRepeat(event, now, repeatCount,
                    KeyEvent.FLAG_LONG_PRESS));
        }
        injectKeyEvent(KeyEvent.changeAction(event, KeyEvent.ACTION_UP));
    }
}

Upvotes: 0

BoredT
BoredT

Reputation: 1590

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

Upvotes: 0

JRL
JRL

Reputation: 78023

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

Upvotes: 2

Related Questions