1/* 2 * Copyright (C) 2013 DroidDriver committers 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.google.android.droiddriver.actions; 18 19import android.os.Build; 20import android.os.SystemClock; 21import android.view.KeyEvent; 22 23import com.google.android.droiddriver.UiElement; 24import com.google.android.droiddriver.util.Events; 25import com.google.android.droiddriver.util.Strings; 26 27/** 28 * An action to press a single key. While it is convenient for navigating the 29 * UI, do not overuse it -- the application may interpret key codes in a custom 30 * way and, more importantly, application users may not have access to it 31 * because the device (physical or virtual keyboard) may not support all key 32 * codes. 33 */ 34public class SingleKeyAction extends KeyAction { 35 /** 36 * Common instances for convenience and memory preservation. 37 */ 38 public static final SingleKeyAction MENU = new SingleKeyAction(KeyEvent.KEYCODE_MENU); 39 public static final SingleKeyAction SEARCH = new SingleKeyAction(KeyEvent.KEYCODE_SEARCH); 40 public static final SingleKeyAction BACK = new SingleKeyAction(KeyEvent.KEYCODE_BACK); 41 public static final SingleKeyAction DELETE = new SingleKeyAction(KeyEvent.KEYCODE_DEL); 42 43 private final int keyCode; 44 45 /** 46 * Defaults timeoutMillis to 100. 47 */ 48 public SingleKeyAction(int keyCode) { 49 this(keyCode, 100L, false); 50 } 51 52 public SingleKeyAction(int keyCode, long timeoutMillis, boolean checkFocused) { 53 super(timeoutMillis, checkFocused); 54 this.keyCode = keyCode; 55 } 56 57 @Override 58 public boolean perform(InputInjector injector, UiElement element) { 59 maybeCheckFocused(element); 60 61 final long downTime = SystemClock.uptimeMillis(); 62 KeyEvent downEvent = Events.newKeyEvent(downTime, KeyEvent.ACTION_DOWN, keyCode); 63 KeyEvent upEvent = Events.newKeyEvent(downTime, KeyEvent.ACTION_UP, keyCode); 64 65 return injector.injectInputEvent(downEvent) && injector.injectInputEvent(upEvent); 66 } 67 68 @Override 69 public String toString() { 70 String keyCodeString = 71 Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1 ? String.valueOf(keyCode) 72 : KeyEvent.keyCodeToString(keyCode); 73 return Strings.toStringHelper(this).addValue(keyCodeString).toString(); 74 } 75} 76