1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.chromium.content.browser.test.util;
7 import android.app.Instrumentation;
8 import android.os.SystemClock;
9 import android.view.KeyEvent;
10 import android.view.View;
12 import org.chromium.base.ThreadUtils;
15 * Collection of keyboard utilities.
17 public class KeyUtils {
19 * Sends (synchronously) a single key down/up pair of events to the specified view.
21 * Does not use the event injecting framework, but instead relies on
22 * {@link View#dispatchKeyEventPreIme(KeyEvent)} and {@link View#dispatchKeyEvent(KeyEvent)} of
25 * The event injecting framework requires INJECT_EVENTS permission and that has been flaky on
26 * our perf bots. So until a root cause of the issue can be found, we should use this instead
27 * of the functionality provided by {@link #sendKeys(int...)}.
29 * @param i The application being instrumented.
30 * @param v The view to receive the key event.
31 * @param keyCode The keycode for the event to be issued.
33 public static void singleKeyEventView(Instrumentation i, final View v, int keyCode) {
34 long downTime = SystemClock.uptimeMillis();
35 long eventTime = SystemClock.uptimeMillis();
37 final KeyEvent downEvent =
38 new KeyEvent(downTime, eventTime, KeyEvent.ACTION_DOWN, keyCode, 0);
39 dispatchKeyEvent(i, v, downEvent);
41 downTime = SystemClock.uptimeMillis();
42 eventTime = SystemClock.uptimeMillis();
43 final KeyEvent upEvent =
44 new KeyEvent(downTime, eventTime, KeyEvent.ACTION_UP, keyCode, 0);
45 dispatchKeyEvent(i, v, upEvent);
48 private static void dispatchKeyEvent(final Instrumentation i, final View v,
49 final KeyEvent event) {
50 ThreadUtils.runOnUiThreadBlocking(new Runnable() {
53 if (!v.dispatchKeyEventPreIme(event)) {
54 v.dispatchKeyEvent(event);