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.SystemClock; 20import android.view.KeyEvent; 21 22import com.google.android.droiddriver.InputInjector; 23import com.google.android.droiddriver.UiElement; 24import com.google.android.droiddriver.util.Events; 25import com.google.common.base.Objects; 26 27/** 28 * An action to press a single key. TODO: rename to SingleKeyAction 29 */ 30public class PressKeyAction extends KeyAction { 31 private final int keyCode; 32 33 /** 34 * Defaults timeoutMillis to 0. 35 */ 36 public PressKeyAction(int keyCode) { 37 this(keyCode, 0L); 38 } 39 40 public PressKeyAction(int keyCode, long timeoutMillis) { 41 super(timeoutMillis); 42 this.keyCode = keyCode; 43 } 44 45 @Override 46 public boolean perform(InputInjector injector, UiElement element) { 47 final long downTime = SystemClock.uptimeMillis(); 48 KeyEvent downEvent = Events.newKeyEvent(downTime, KeyEvent.ACTION_DOWN, keyCode); 49 KeyEvent upEvent = Events.newKeyEvent(downTime, KeyEvent.ACTION_UP, keyCode); 50 51 return injector.injectInputEvent(downEvent) && injector.injectInputEvent(upEvent); 52 } 53 54 @Override 55 public String toString() { 56 return Objects.toStringHelper(this).addValue(KeyEvent.keyCodeToString(keyCode)).toString(); 57 } 58} 59