How do you send a long press from an InstrumentationTestCase?
In Andr开发者_如何学编程oid, 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.
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));
}
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);
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));
}
}
精彩评论