Debian Codegraph @

core/java/android/view/KeyEvent.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 The Android Open Source Project
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
17 package android.view;
18
19 import static android.os.IInputConstants.INPUT_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
20 import static android.view.Display.INVALID_DISPLAY;
21
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.TestApi;
25 import android.compat.annotation.UnsupportedAppUsage;
26 import android.os.Build;
27 import android.os.Parcel;
28 import android.os.Parcelable;
29 import android.text.method.MetaKeyKeyListener;
30 import android.util.Log;
31 import android.util.SparseIntArray;
32 import android.view.KeyCharacterMap.KeyData;
33
34 import java.util.concurrent.TimeUnit;
35
36 /**
37 * Object used to report key and button events.
38 * <p>
39 * Each key press is described by a sequence of key events. A key press
40 * starts with a key event with {@link #ACTION_DOWN}. If the key is held
41 * sufficiently long that it repeats, then the initial down is followed
42 * additional key events with {@link #ACTION_DOWN} and a non-zero value for
43 * {@link #getRepeatCount()}. The last key event is a {@link #ACTION_UP}
44 * for the key up. If the key press is canceled, the key up event will have the
45 * {@link #FLAG_CANCELED} flag set.
46 * </p><p>
47 * Key events are generally accompanied by a key code ({@link #getKeyCode()}),
48 * scan code ({@link #getScanCode()}) and meta state ({@link #getMetaState()}).
49 * Key code constants are defined in this class. Scan code constants are raw
50 * device-specific codes obtained from the OS and so are not generally meaningful
51 * to applications unless interpreted using the {@link KeyCharacterMap}.
52 * Meta states describe the pressed state of key modifiers
53 * such as {@link #META_SHIFT_ON} or {@link #META_ALT_ON}.
54 * </p><p>
55 * Key codes typically correspond one-to-one with individual keys on an input device.
56 * Many keys and key combinations serve quite different functions on different
57 * input devices so care must be taken when interpreting them. Always use the
58 * {@link KeyCharacterMap} associated with the input device when mapping keys
59 * to characters. Be aware that there may be multiple key input devices active
60 * at the same time and each will have its own key character map.
61 * </p><p>
62 * As soft input methods can use multiple and inventive ways of inputting text,
63 * there is no guarantee that any key press on a soft keyboard will generate a key
64 * event: this is left to the IME's discretion, and in fact sending such events is
65 * discouraged. You should never rely on receiving KeyEvents for any key on a soft
66 * input method. In particular, the default software keyboard will never send any
67 * key event to any application targetting Jelly Bean or later, and will only send
68 * events for some presses of the delete and return keys to applications targetting
69 * Ice Cream Sandwich or earlier. Be aware that other software input methods may
70 * never send key events regardless of the version. Consider using editor actions
71 * like {@link android.view.inputmethod.EditorInfo#IME_ACTION_DONE} if you need
72 * specific interaction with the software keyboard, as it gives more visibility to
73 * the user as to how your application will react to key presses.
74 * </p><p>
75 * When interacting with an IME, the framework may deliver key events
76 * with the special action {@link #ACTION_MULTIPLE} that either specifies
77 * that single repeated key code or a sequence of characters to insert.
78 * </p><p>
79 * In general, the framework cannot guarantee that the key events it delivers
80 * to a view always constitute complete key sequences since some events may be dropped
81 * or modified by containing views before they are delivered. The view implementation
82 * should be prepared to handle {@link #FLAG_CANCELED} and should tolerate anomalous
83 * situations such as receiving a new {@link #ACTION_DOWN} without first having
84 * received an {@link #ACTION_UP} for the prior key press.
85 * </p><p>
86 * Refer to {@link InputDevice} for more information about how different kinds of
87 * input devices and sources represent keys and buttons.
88 * </p>
89 */
90 public class KeyEvent extends InputEvent implements Parcelable {
91 /** Key code constant: Unknown key code. */
92 public static final int KEYCODE_UNKNOWN = 0;
93 /** Key code constant: Soft Left key.
94 * Usually situated below the display on phones and used as a multi-function
95 * feature key for selecting a software defined function shown on the bottom left
96 * of the display. */
97 public static final int KEYCODE_SOFT_LEFT = 1;
98 /** Key code constant: Soft Right key.
99 * Usually situated below the display on phones and used as a multi-function
100 * feature key for selecting a software defined function shown on the bottom right
101 * of the display. */
102 public static final int KEYCODE_SOFT_RIGHT = 2;
103 /** Key code constant: Home key.
104 * This key is handled by the framework and is never delivered to applications. */
105 public static final int KEYCODE_HOME = 3;
106 /** Key code constant: Back key. */
107 public static final int KEYCODE_BACK = 4;
108 /** Key code constant: Call key. */
109 public static final int KEYCODE_CALL = 5;
110 /** Key code constant: End Call key. */
111 public static final int KEYCODE_ENDCALL = 6;
112 /** Key code constant: '0' key. */
113 public static final int KEYCODE_0 = 7;
114 /** Key code constant: '1' key. */
115 public static final int KEYCODE_1 = 8;
116 /** Key code constant: '2' key. */
117 public static final int KEYCODE_2 = 9;
118 /** Key code constant: '3' key. */
119 public static final int KEYCODE_3 = 10;
120 /** Key code constant: '4' key. */
121 public static final int KEYCODE_4 = 11;
122 /** Key code constant: '5' key. */
123 public static final int KEYCODE_5 = 12;
124 /** Key code constant: '6' key. */
125 public static final int KEYCODE_6 = 13;
126 /** Key code constant: '7' key. */
127 public static final int KEYCODE_7 = 14;
128 /** Key code constant: '8' key. */
129 public static final int KEYCODE_8 = 15;
130 /** Key code constant: '9' key. */
131 public static final int KEYCODE_9 = 16;
132 /** Key code constant: '*' key. */
133 public static final int KEYCODE_STAR = 17;
134 /** Key code constant: '#' key. */
135 public static final int KEYCODE_POUND = 18;
136 /** Key code constant: Directional Pad Up key.
137 * May also be synthesized from trackball motions. */
138 public static final int KEYCODE_DPAD_UP = 19;
139 /** Key code constant: Directional Pad Down key.
140 * May also be synthesized from trackball motions. */
141 public static final int KEYCODE_DPAD_DOWN = 20;
142 /** Key code constant: Directional Pad Left key.
143 * May also be synthesized from trackball motions. */
144 public static final int KEYCODE_DPAD_LEFT = 21;
145 /** Key code constant: Directional Pad Right key.
146 * May also be synthesized from trackball motions. */
147 public static final int KEYCODE_DPAD_RIGHT = 22;
148 /** Key code constant: Directional Pad Center key.
149 * May also be synthesized from trackball motions. */
150 public static final int KEYCODE_DPAD_CENTER = 23;
151 /** Key code constant: Volume Up key.
152 * Adjusts the speaker volume up. */
153 public static final int KEYCODE_VOLUME_UP = 24;
154 /** Key code constant: Volume Down key.
155 * Adjusts the speaker volume down. */
156 public static final int KEYCODE_VOLUME_DOWN = 25;
157 /** Key code constant: Power key. */
158 public static final int KEYCODE_POWER = 26;
159 /** Key code constant: Camera key.
160 * Used to launch a camera application or take pictures. */
161 public static final int KEYCODE_CAMERA = 27;
162 /** Key code constant: Clear key. */
163 public static final int KEYCODE_CLEAR = 28;
164 /** Key code constant: 'A' key. */
165 public static final int KEYCODE_A = 29;
166 /** Key code constant: 'B' key. */
167 public static final int KEYCODE_B = 30;
168 /** Key code constant: 'C' key. */
169 public static final int KEYCODE_C = 31;
170 /** Key code constant: 'D' key. */
171 public static final int KEYCODE_D = 32;
172 /** Key code constant: 'E' key. */
173 public static final int KEYCODE_E = 33;
174 /** Key code constant: 'F' key. */
175 public static final int KEYCODE_F = 34;
176 /** Key code constant: 'G' key. */
177 public static final int KEYCODE_G = 35;
178 /** Key code constant: 'H' key. */
179 public static final int KEYCODE_H = 36;
180 /** Key code constant: 'I' key. */
181 public static final int KEYCODE_I = 37;
182 /** Key code constant: 'J' key. */
183 public static final int KEYCODE_J = 38;
184 /** Key code constant: 'K' key. */
185 public static final int KEYCODE_K = 39;
186 /** Key code constant: 'L' key. */
187 public static final int KEYCODE_L = 40;
188 /** Key code constant: 'M' key. */
189 public static final int KEYCODE_M = 41;
190 /** Key code constant: 'N' key. */
191 public static final int KEYCODE_N = 42;
192 /** Key code constant: 'O' key. */
193 public static final int KEYCODE_O = 43;
194 /** Key code constant: 'P' key. */
195 public static final int KEYCODE_P = 44;
196 /** Key code constant: 'Q' key. */
197 public static final int KEYCODE_Q = 45;
198 /** Key code constant: 'R' key. */
199 public static final int KEYCODE_R = 46;
200 /** Key code constant: 'S' key. */
201 public static final int KEYCODE_S = 47;
202 /** Key code constant: 'T' key. */
203 public static final int KEYCODE_T = 48;
204 /** Key code constant: 'U' key. */
205 public static final int KEYCODE_U = 49;
206 /** Key code constant: 'V' key. */
207 public static final int KEYCODE_V = 50;
208 /** Key code constant: 'W' key. */
209 public static final int KEYCODE_W = 51;
210 /** Key code constant: 'X' key. */
211 public static final int KEYCODE_X = 52;
212 /** Key code constant: 'Y' key. */
213 public static final int KEYCODE_Y = 53;
214 /** Key code constant: 'Z' key. */
215 public static final int KEYCODE_Z = 54;
216 /** Key code constant: ',' key. */
217 public static final int KEYCODE_COMMA = 55;
218 /** Key code constant: '.' key. */
219 public static final int KEYCODE_PERIOD = 56;
220 /** Key code constant: Left Alt modifier key. */
221 public static final int KEYCODE_ALT_LEFT = 57;
222 /** Key code constant: Right Alt modifier key. */
223 public static final int KEYCODE_ALT_RIGHT = 58;
224 /** Key code constant: Left Shift modifier key. */
225 public static final int KEYCODE_SHIFT_LEFT = 59;
226 /** Key code constant: Right Shift modifier key. */
227 public static final int KEYCODE_SHIFT_RIGHT = 60;
228 /** Key code constant: Tab key. */
229 public static final int KEYCODE_TAB = 61;
230 /** Key code constant: Space key. */
231 public static final int KEYCODE_SPACE = 62;
232 /** Key code constant: Symbol modifier key.
233 * Used to enter alternate symbols. */
234 public static final int KEYCODE_SYM = 63;
235 /** Key code constant: Explorer special function key.
236 * Used to launch a browser application. */
237 public static final int KEYCODE_EXPLORER = 64;
238 /** Key code constant: Envelope special function key.
239 * Used to launch a mail application. */
240 public static final int KEYCODE_ENVELOPE = 65;
241 /** Key code constant: Enter key. */
242 public static final int KEYCODE_ENTER = 66;
243 /** Key code constant: Backspace key.
244 * Deletes characters before the insertion point, unlike {@link #KEYCODE_FORWARD_DEL}. */
245 public static final int KEYCODE_DEL = 67;
246 /** Key code constant: '`' (backtick) key. */
247 public static final int KEYCODE_GRAVE = 68;
248 /** Key code constant: '-'. */
249 public static final int KEYCODE_MINUS = 69;
250 /** Key code constant: '=' key. */
251 public static final int KEYCODE_EQUALS = 70;
252 /** Key code constant: '[' key. */
253 public static final int KEYCODE_LEFT_BRACKET = 71;
254 /** Key code constant: ']' key. */
255 public static final int KEYCODE_RIGHT_BRACKET = 72;
256 /** Key code constant: '\' key. */
257 public static final int KEYCODE_BACKSLASH = 73;
258 /** Key code constant: ';' key. */
259 public static final int KEYCODE_SEMICOLON = 74;
260 /** Key code constant: ''' (apostrophe) key. */
261 public static final int KEYCODE_APOSTROPHE = 75;
262 /** Key code constant: '/' key. */
263 public static final int KEYCODE_SLASH = 76;
264 /** Key code constant: '@' key. */
265 public static final int KEYCODE_AT = 77;
266 /** Key code constant: Number modifier key.
267 * Used to enter numeric symbols.
268 * This key is not Num Lock; it is more like {@link #KEYCODE_ALT_LEFT} and is
269 * interpreted as an ALT key by {@link android.text.method.MetaKeyKeyListener}. */
270 public static final int KEYCODE_NUM = 78;
271 /** Key code constant: Headset Hook key.
272 * Used to hang up calls and stop media. */
273 public static final int KEYCODE_HEADSETHOOK = 79;
274 /** Key code constant: Camera Focus key.
275 * Used to focus the camera. */
276 public static final int KEYCODE_FOCUS = 80; // *Camera* focus
277 /** Key code constant: '+' key. */
278 public static final int KEYCODE_PLUS = 81;
279 /** Key code constant: Menu key. */
280 public static final int KEYCODE_MENU = 82;
281 /** Key code constant: Notification key. */
282 public static final int KEYCODE_NOTIFICATION = 83;
283 /** Key code constant: Search key. */
284 public static final int KEYCODE_SEARCH = 84;
285 /** Key code constant: Play/Pause media key. */
286 public static final int KEYCODE_MEDIA_PLAY_PAUSE= 85;
287 /** Key code constant: Stop media key. */
288 public static final int KEYCODE_MEDIA_STOP = 86;
289 /** Key code constant: Play Next media key. */
290 public static final int KEYCODE_MEDIA_NEXT = 87;
291 /** Key code constant: Play Previous media key. */
292 public static final int KEYCODE_MEDIA_PREVIOUS = 88;
293 /** Key code constant: Rewind media key. */
294 public static final int KEYCODE_MEDIA_REWIND = 89;
295 /** Key code constant: Fast Forward media key. */
296 public static final int KEYCODE_MEDIA_FAST_FORWARD = 90;
297 /** Key code constant: Mute key.
298 * Mute key for the microphone (unlike {@link #KEYCODE_VOLUME_MUTE}, which is the speaker mute
299 * key). */
300 public static final int KEYCODE_MUTE = 91;
301 /** Key code constant: Page Up key. */
302 public static final int KEYCODE_PAGE_UP = 92;
303 /** Key code constant: Page Down key. */
304 public static final int KEYCODE_PAGE_DOWN = 93;
305 /** Key code constant: Picture Symbols modifier key.
306 * Used to switch symbol sets (Emoji, Kao-moji). */
307 public static final int KEYCODE_PICTSYMBOLS = 94; // switch symbol-sets (Emoji,Kao-moji)
308 /** Key code constant: Switch Charset modifier key.
309 * Used to switch character sets (Kanji, Katakana). */
310 public static final int KEYCODE_SWITCH_CHARSET = 95; // switch char-sets (Kanji,Katakana)
311 /** Key code constant: A Button key.
312 * On a game controller, the A button should be either the button labeled A
313 * or the first button on the bottom row of controller buttons. */
314 public static final int KEYCODE_BUTTON_A = 96;
315 /** Key code constant: B Button key.
316 * On a game controller, the B button should be either the button labeled B
317 * or the second button on the bottom row of controller buttons. */
318 public static final int KEYCODE_BUTTON_B = 97;
319 /** Key code constant: C Button key.
320 * On a game controller, the C button should be either the button labeled C
321 * or the third button on the bottom row of controller buttons. */
322 public static final int KEYCODE_BUTTON_C = 98;
323 /** Key code constant: X Button key.
324 * On a game controller, the X button should be either the button labeled X
325 * or the first button on the upper row of controller buttons. */
326 public static final int KEYCODE_BUTTON_X = 99;
327 /** Key code constant: Y Button key.
328 * On a game controller, the Y button should be either the button labeled Y
329 * or the second button on the upper row of controller buttons. */
330 public static final int KEYCODE_BUTTON_Y = 100;
331 /** Key code constant: Z Button key.
332 * On a game controller, the Z button should be either the button labeled Z
333 * or the third button on the upper row of controller buttons. */
334 public static final int KEYCODE_BUTTON_Z = 101;
335 /** Key code constant: L1 Button key.
336 * On a game controller, the L1 button should be either the button labeled L1 (or L)
337 * or the top left trigger button. */
338 public static final int KEYCODE_BUTTON_L1 = 102;
339 /** Key code constant: R1 Button key.
340 * On a game controller, the R1 button should be either the button labeled R1 (or R)
341 * or the top right trigger button. */
342 public static final int KEYCODE_BUTTON_R1 = 103;
343 /** Key code constant: L2 Button key.
344 * On a game controller, the L2 button should be either the button labeled L2
345 * or the bottom left trigger button. */
346 public static final int KEYCODE_BUTTON_L2 = 104;
347 /** Key code constant: R2 Button key.
348 * On a game controller, the R2 button should be either the button labeled R2
349 * or the bottom right trigger button. */
350 public static final int KEYCODE_BUTTON_R2 = 105;
351 /** Key code constant: Left Thumb Button key.
352 * On a game controller, the left thumb button indicates that the left (or only)
353 * joystick is pressed. */
354 public static final int KEYCODE_BUTTON_THUMBL = 106;
355 /** Key code constant: Right Thumb Button key.
356 * On a game controller, the right thumb button indicates that the right
357 * joystick is pressed. */
358 public static final int KEYCODE_BUTTON_THUMBR = 107;
359 /** Key code constant: Start Button key.
360 * On a game controller, the button labeled Start. */
361 public static final int KEYCODE_BUTTON_START = 108;
362 /** Key code constant: Select Button key.
363 * On a game controller, the button labeled Select. */
364 public static final int KEYCODE_BUTTON_SELECT = 109;
365 /** Key code constant: Mode Button key.
366 * On a game controller, the button labeled Mode. */
367 public static final int KEYCODE_BUTTON_MODE = 110;
368 /** Key code constant: Escape key. */
369 public static final int KEYCODE_ESCAPE = 111;
370 /** Key code constant: Forward Delete key.
371 * Deletes characters ahead of the insertion point, unlike {@link #KEYCODE_DEL}. */
372 public static final int KEYCODE_FORWARD_DEL = 112;
373 /** Key code constant: Left Control modifier key. */
374 public static final int KEYCODE_CTRL_LEFT = 113;
375 /** Key code constant: Right Control modifier key. */
376 public static final int KEYCODE_CTRL_RIGHT = 114;
377 /** Key code constant: Caps Lock key. */
378 public static final int KEYCODE_CAPS_LOCK = 115;
379 /** Key code constant: Scroll Lock key. */
380 public static final int KEYCODE_SCROLL_LOCK = 116;
381 /** Key code constant: Left Meta modifier key. */
382 public static final int KEYCODE_META_LEFT = 117;
383 /** Key code constant: Right Meta modifier key. */
384 public static final int KEYCODE_META_RIGHT = 118;
385 /** Key code constant: Function modifier key. */
386 public static final int KEYCODE_FUNCTION = 119;
387 /** Key code constant: System Request / Print Screen key. */
388 public static final int KEYCODE_SYSRQ = 120;
389 /** Key code constant: Break / Pause key. */
390 public static final int KEYCODE_BREAK = 121;
391 /** Key code constant: Home Movement key.
392 * Used for scrolling or moving the cursor around to the start of a line
393 * or to the top of a list. */
394 public static final int KEYCODE_MOVE_HOME = 122;
395 /** Key code constant: End Movement key.
396 * Used for scrolling or moving the cursor around to the end of a line
397 * or to the bottom of a list. */
398 public static final int KEYCODE_MOVE_END = 123;
399 /** Key code constant: Insert key.
400 * Toggles insert / overwrite edit mode. */
401 public static final int KEYCODE_INSERT = 124;
402 /** Key code constant: Forward key.
403 * Navigates forward in the history stack. Complement of {@link #KEYCODE_BACK}. */
404 public static final int KEYCODE_FORWARD = 125;
405 /** Key code constant: Play media key. */
406 public static final int KEYCODE_MEDIA_PLAY = 126;
407 /** Key code constant: Pause media key. */
408 public static final int KEYCODE_MEDIA_PAUSE = 127;
409 /** Key code constant: Close media key.
410 * May be used to close a CD tray, for example. */
411 public static final int KEYCODE_MEDIA_CLOSE = 128;
412 /** Key code constant: Eject media key.
413 * May be used to eject a CD tray, for example. */
414 public static final int KEYCODE_MEDIA_EJECT = 129;
415 /** Key code constant: Record media key. */
416 public static final int KEYCODE_MEDIA_RECORD = 130;
417 /** Key code constant: F1 key. */
418 public static final int KEYCODE_F1 = 131;
419 /** Key code constant: F2 key. */
420 public static final int KEYCODE_F2 = 132;
421 /** Key code constant: F3 key. */
422 public static final int KEYCODE_F3 = 133;
423 /** Key code constant: F4 key. */
424 public static final int KEYCODE_F4 = 134;
425 /** Key code constant: F5 key. */
426 public static final int KEYCODE_F5 = 135;
427 /** Key code constant: F6 key. */
428 public static final int KEYCODE_F6 = 136;
429 /** Key code constant: F7 key. */
430 public static final int KEYCODE_F7 = 137;
431 /** Key code constant: F8 key. */
432 public static final int KEYCODE_F8 = 138;
433 /** Key code constant: F9 key. */
434 public static final int KEYCODE_F9 = 139;
435 /** Key code constant: F10 key. */
436 public static final int KEYCODE_F10 = 140;
437 /** Key code constant: F11 key. */
438 public static final int KEYCODE_F11 = 141;
439 /** Key code constant: F12 key. */
440 public static final int KEYCODE_F12 = 142;
441 /** Key code constant: Num Lock key.
442 * This is the Num Lock key; it is different from {@link #KEYCODE_NUM}.
443 * This key alters the behavior of other keys on the numeric keypad. */
444 public static final int KEYCODE_NUM_LOCK = 143;
445 /** Key code constant: Numeric keypad '0' key. */
446 public static final int KEYCODE_NUMPAD_0 = 144;
447 /** Key code constant: Numeric keypad '1' key. */
448 public static final int KEYCODE_NUMPAD_1 = 145;
449 /** Key code constant: Numeric keypad '2' key. */
450 public static final int KEYCODE_NUMPAD_2 = 146;
451 /** Key code constant: Numeric keypad '3' key. */
452 public static final int KEYCODE_NUMPAD_3 = 147;
453 /** Key code constant: Numeric keypad '4' key. */
454 public static final int KEYCODE_NUMPAD_4 = 148;
455 /** Key code constant: Numeric keypad '5' key. */
456 public static final int KEYCODE_NUMPAD_5 = 149;
457 /** Key code constant: Numeric keypad '6' key. */
458 public static final int KEYCODE_NUMPAD_6 = 150;
459 /** Key code constant: Numeric keypad '7' key. */
460 public static final int KEYCODE_NUMPAD_7 = 151;
461 /** Key code constant: Numeric keypad '8' key. */
462 public static final int KEYCODE_NUMPAD_8 = 152;
463 /** Key code constant: Numeric keypad '9' key. */
464 public static final int KEYCODE_NUMPAD_9 = 153;
465 /** Key code constant: Numeric keypad '/' key (for division). */
466 public static final int KEYCODE_NUMPAD_DIVIDE = 154;
467 /** Key code constant: Numeric keypad '*' key (for multiplication). */
468 public static final int KEYCODE_NUMPAD_MULTIPLY = 155;
469 /** Key code constant: Numeric keypad '-' key (for subtraction). */
470 public static final int KEYCODE_NUMPAD_SUBTRACT = 156;
471 /** Key code constant: Numeric keypad '+' key (for addition). */
472 public static final int KEYCODE_NUMPAD_ADD = 157;
473 /** Key code constant: Numeric keypad '.' key (for decimals or digit grouping). */
474 public static final int KEYCODE_NUMPAD_DOT = 158;
475 /** Key code constant: Numeric keypad ',' key (for decimals or digit grouping). */
476 public static final int KEYCODE_NUMPAD_COMMA = 159;
477 /** Key code constant: Numeric keypad Enter key. */
478 public static final int KEYCODE_NUMPAD_ENTER = 160;
479 /** Key code constant: Numeric keypad '=' key. */
480 public static final int KEYCODE_NUMPAD_EQUALS = 161;
481 /** Key code constant: Numeric keypad '(' key. */
482 public static final int KEYCODE_NUMPAD_LEFT_PAREN = 162;
483 /** Key code constant: Numeric keypad ')' key. */
484 public static final int KEYCODE_NUMPAD_RIGHT_PAREN = 163;
485 /** Key code constant: Volume Mute key.
486 * Mute key for speaker (unlike {@link #KEYCODE_MUTE}, which is the mute key for the
487 * microphone). This key should normally be implemented as a toggle such that the first press
488 * mutes the speaker and the second press restores the original volume.
489 */
490 public static final int KEYCODE_VOLUME_MUTE = 164;
491 /** Key code constant: Info key.
492 * Common on TV remotes to show additional information related to what is
493 * currently being viewed. */
494 public static final int KEYCODE_INFO = 165;
495 /** Key code constant: Channel up key.
496 * On TV remotes, increments the television channel. */
497 public static final int KEYCODE_CHANNEL_UP = 166;
498 /** Key code constant: Channel down key.
499 * On TV remotes, decrements the television channel. */
500 public static final int KEYCODE_CHANNEL_DOWN = 167;
501 /** Key code constant: Zoom in key. */
502 public static final int KEYCODE_ZOOM_IN = 168;
503 /** Key code constant: Zoom out key. */
504 public static final int KEYCODE_ZOOM_OUT = 169;
505 /** Key code constant: TV key.
506 * On TV remotes, switches to viewing live TV. */
507 public static final int KEYCODE_TV = 170;
508 /** Key code constant: Window key.
509 * On TV remotes, toggles picture-in-picture mode or other windowing functions.
510 * On Android Wear devices, triggers a display offset. */
511 public static final int KEYCODE_WINDOW = 171;
512 /** Key code constant: Guide key.
513 * On TV remotes, shows a programming guide. */
514 public static final int KEYCODE_GUIDE = 172;
515 /** Key code constant: DVR key.
516 * On some TV remotes, switches to a DVR mode for recorded shows. */
517 public static final int KEYCODE_DVR = 173;
518 /** Key code constant: Bookmark key.
519 * On some TV remotes, bookmarks content or web pages. */
520 public static final int KEYCODE_BOOKMARK = 174;
521 /** Key code constant: Toggle captions key.
522 * Switches the mode for closed-captioning text, for example during television shows. */
523 public static final int KEYCODE_CAPTIONS = 175;
524 /** Key code constant: Settings key.
525 * Starts the system settings activity. */
526 public static final int KEYCODE_SETTINGS = 176;
527 /**
528 * Key code constant: TV power key.
529 * On HDMI TV panel devices and Android TV devices that don't support HDMI, toggles the power
530 * state of the device.
531 * On HDMI source devices, toggles the power state of the HDMI-connected TV via HDMI-CEC and
532 * makes the source device follow this power state.
533 */
534 public static final int KEYCODE_TV_POWER = 177;
535 /** Key code constant: TV input key.
536 * On TV remotes, switches the input on a television screen. */
537 public static final int KEYCODE_TV_INPUT = 178;
538 /** Key code constant: Set-top-box power key.
539 * On TV remotes, toggles the power on an external Set-top-box. */
540 public static final int KEYCODE_STB_POWER = 179;
541 /** Key code constant: Set-top-box input key.
542 * On TV remotes, switches the input mode on an external Set-top-box. */
543 public static final int KEYCODE_STB_INPUT = 180;
544 /** Key code constant: A/V Receiver power key.
545 * On TV remotes, toggles the power on an external A/V Receiver. */
546 public static final int KEYCODE_AVR_POWER = 181;
547 /** Key code constant: A/V Receiver input key.
548 * On TV remotes, switches the input mode on an external A/V Receiver. */
549 public static final int KEYCODE_AVR_INPUT = 182;
550 /** Key code constant: Red "programmable" key.
551 * On TV remotes, acts as a contextual/programmable key. */
552 public static final int KEYCODE_PROG_RED = 183;
553 /** Key code constant: Green "programmable" key.
554 * On TV remotes, actsas a contextual/programmable key. */
555 public static final int KEYCODE_PROG_GREEN = 184;
556 /** Key code constant: Yellow "programmable" key.
557 * On TV remotes, acts as a contextual/programmable key. */
558 public static final int KEYCODE_PROG_YELLOW = 185;
559 /** Key code constant: Blue "programmable" key.
560 * On TV remotes, acts as a contextual/programmable key. */
561 public static final int KEYCODE_PROG_BLUE = 186;
562 /** Key code constant: App switch key.
563 * Should bring up the application switcher dialog. */
564 public static final int KEYCODE_APP_SWITCH = 187;
565 /** Key code constant: Generic Game Pad Button #1.*/
566 public static final int KEYCODE_BUTTON_1 = 188;
567 /** Key code constant: Generic Game Pad Button #2.*/
568 public static final int KEYCODE_BUTTON_2 = 189;
569 /** Key code constant: Generic Game Pad Button #3.*/
570 public static final int KEYCODE_BUTTON_3 = 190;
571 /** Key code constant: Generic Game Pad Button #4.*/
572 public static final int KEYCODE_BUTTON_4 = 191;
573 /** Key code constant: Generic Game Pad Button #5.*/
574 public static final int KEYCODE_BUTTON_5 = 192;
575 /** Key code constant: Generic Game Pad Button #6.*/
576 public static final int KEYCODE_BUTTON_6 = 193;
577 /** Key code constant: Generic Game Pad Button #7.*/
578 public static final int KEYCODE_BUTTON_7 = 194;
579 /** Key code constant: Generic Game Pad Button #8.*/
580 public static final int KEYCODE_BUTTON_8 = 195;
581 /** Key code constant: Generic Game Pad Button #9.*/
582 public static final int KEYCODE_BUTTON_9 = 196;
583 /** Key code constant: Generic Game Pad Button #10.*/
584 public static final int KEYCODE_BUTTON_10 = 197;
585 /** Key code constant: Generic Game Pad Button #11.*/
586 public static final int KEYCODE_BUTTON_11 = 198;
587 /** Key code constant: Generic Game Pad Button #12.*/
588 public static final int KEYCODE_BUTTON_12 = 199;
589 /** Key code constant: Generic Game Pad Button #13.*/
590 public static final int KEYCODE_BUTTON_13 = 200;
591 /** Key code constant: Generic Game Pad Button #14.*/
592 public static final int KEYCODE_BUTTON_14 = 201;
593 /** Key code constant: Generic Game Pad Button #15.*/
594 public static final int KEYCODE_BUTTON_15 = 202;
595 /** Key code constant: Generic Game Pad Button #16.*/
596 public static final int KEYCODE_BUTTON_16 = 203;
597 /** Key code constant: Language Switch key.
598 * Toggles the current input language such as switching between English and Japanese on
599 * a QWERTY keyboard. On some devices, the same function may be performed by
600 * pressing Shift+Spacebar. */
601 public static final int KEYCODE_LANGUAGE_SWITCH = 204;
602 /** Key code constant: Manner Mode key.
603 * Toggles silent or vibrate mode on and off to make the device behave more politely
604 * in certain settings such as on a crowded train. On some devices, the key may only
605 * operate when long-pressed. */
606 public static final int KEYCODE_MANNER_MODE = 205;
607 /** Key code constant: 3D Mode key.
608 * Toggles the display between 2D and 3D mode. */
609 public static final int KEYCODE_3D_MODE = 206;
610 /** Key code constant: Contacts special function key.
611 * Used to launch an address book application. */
612 public static final int KEYCODE_CONTACTS = 207;
613 /** Key code constant: Calendar special function key.
614 * Used to launch a calendar application. */
615 public static final int KEYCODE_CALENDAR = 208;
616 /** Key code constant: Music special function key.
617 * Used to launch a music player application. */
618 public static final int KEYCODE_MUSIC = 209;
619 /** Key code constant: Calculator special function key.
620 * Used to launch a calculator application. */
621 public static final int KEYCODE_CALCULATOR = 210;
622 /** Key code constant: Japanese full-width / half-width key. */
623 public static final int KEYCODE_ZENKAKU_HANKAKU = 211;
624 /** Key code constant: Japanese alphanumeric key. */
625 public static final int KEYCODE_EISU = 212;
626 /** Key code constant: Japanese non-conversion key. */
627 public static final int KEYCODE_MUHENKAN = 213;
628 /** Key code constant: Japanese conversion key. */
629 public static final int KEYCODE_HENKAN = 214;
630 /** Key code constant: Japanese katakana / hiragana key. */
631 public static final int KEYCODE_KATAKANA_HIRAGANA = 215;
632 /** Key code constant: Japanese Yen key. */
633 public static final int KEYCODE_YEN = 216;
634 /** Key code constant: Japanese Ro key. */
635 public static final int KEYCODE_RO = 217;
636 /** Key code constant: Japanese kana key. */
637 public static final int KEYCODE_KANA = 218;
638 /** Key code constant: Assist key.
639 * Launches the global assist activity. Not delivered to applications. */
640 public static final int KEYCODE_ASSIST = 219;
641 /** Key code constant: Brightness Down key.
642 * Adjusts the screen brightness down. */
643 public static final int KEYCODE_BRIGHTNESS_DOWN = 220;
644 /** Key code constant: Brightness Up key.
645 * Adjusts the screen brightness up. */
646 public static final int KEYCODE_BRIGHTNESS_UP = 221;
647 /** Key code constant: Audio Track key.
648 * Switches the audio tracks. */
649 public static final int KEYCODE_MEDIA_AUDIO_TRACK = 222;
650 /** Key code constant: Sleep key.
651 * Puts the device to sleep. Behaves somewhat like {@link #KEYCODE_POWER} but it
652 * has no effect if the device is already asleep. */
653 public static final int KEYCODE_SLEEP = 223;
654 /** Key code constant: Wakeup key.
655 * Wakes up the device. Behaves somewhat like {@link #KEYCODE_POWER} but it
656 * has no effect if the device is already awake. */
657 public static final int KEYCODE_WAKEUP = 224;
658 /** Key code constant: Pairing key.
659 * Initiates peripheral pairing mode. Useful for pairing remote control
660 * devices or game controllers, especially if no other input mode is
661 * available. */
662 public static final int KEYCODE_PAIRING = 225;
663 /** Key code constant: Media Top Menu key.
664 * Goes to the top of media menu. */
665 public static final int KEYCODE_MEDIA_TOP_MENU = 226;
666 /** Key code constant: '11' key. */
667 public static final int KEYCODE_11 = 227;
668 /** Key code constant: '12' key. */
669 public static final int KEYCODE_12 = 228;
670 /** Key code constant: Last Channel key.
671 * Goes to the last viewed channel. */
672 public static final int KEYCODE_LAST_CHANNEL = 229;
673 /** Key code constant: TV data service key.
674 * Displays data services like weather, sports. */
675 public static final int KEYCODE_TV_DATA_SERVICE = 230;
676 /** Key code constant: Voice Assist key.
677 * Launches the global voice assist activity. Not delivered to applications. */
678 public static final int KEYCODE_VOICE_ASSIST = 231;
679 /** Key code constant: Radio key.
680 * Toggles TV service / Radio service. */
681 public static final int KEYCODE_TV_RADIO_SERVICE = 232;
682 /** Key code constant: Teletext key.
683 * Displays Teletext service. */
684 public static final int KEYCODE_TV_TELETEXT = 233;
685 /** Key code constant: Number entry key.
686 * Initiates to enter multi-digit channel nubmber when each digit key is assigned
687 * for selecting separate channel. Corresponds to Number Entry Mode (0x1D) of CEC
688 * User Control Code. */
689 public static final int KEYCODE_TV_NUMBER_ENTRY = 234;
690 /** Key code constant: Analog Terrestrial key.
691 * Switches to analog terrestrial broadcast service. */
692 public static final int KEYCODE_TV_TERRESTRIAL_ANALOG = 235;
693 /** Key code constant: Digital Terrestrial key.
694 * Switches to digital terrestrial broadcast service. */
695 public static final int KEYCODE_TV_TERRESTRIAL_DIGITAL = 236;
696 /** Key code constant: Satellite key.
697 * Switches to digital satellite broadcast service. */
698 public static final int KEYCODE_TV_SATELLITE = 237;
699 /** Key code constant: BS key.
700 * Switches to BS digital satellite broadcasting service available in Japan. */
701 public static final int KEYCODE_TV_SATELLITE_BS = 238;
702 /** Key code constant: CS key.
703 * Switches to CS digital satellite broadcasting service available in Japan. */
704 public static final int KEYCODE_TV_SATELLITE_CS = 239;
705 /** Key code constant: BS/CS key.
706 * Toggles between BS and CS digital satellite services. */
707 public static final int KEYCODE_TV_SATELLITE_SERVICE = 240;
708 /** Key code constant: Toggle Network key.
709 * Toggles selecting broacast services. */
710 public static final int KEYCODE_TV_NETWORK = 241;
711 /** Key code constant: Antenna/Cable key.
712 * Toggles broadcast input source between antenna and cable. */
713 public static final int KEYCODE_TV_ANTENNA_CABLE = 242;
714 /** Key code constant: HDMI #1 key.
715 * Switches to HDMI input #1. */
716 public static final int KEYCODE_TV_INPUT_HDMI_1 = 243;
717 /** Key code constant: HDMI #2 key.
718 * Switches to HDMI input #2. */
719 public static final int KEYCODE_TV_INPUT_HDMI_2 = 244;
720 /** Key code constant: HDMI #3 key.
721 * Switches to HDMI input #3. */
722 public static final int KEYCODE_TV_INPUT_HDMI_3 = 245;
723 /** Key code constant: HDMI #4 key.
724 * Switches to HDMI input #4. */
725 public static final int KEYCODE_TV_INPUT_HDMI_4 = 246;
726 /** Key code constant: Composite #1 key.
727 * Switches to composite video input #1. */
728 public static final int KEYCODE_TV_INPUT_COMPOSITE_1 = 247;
729 /** Key code constant: Composite #2 key.
730 * Switches to composite video input #2. */
731 public static final int KEYCODE_TV_INPUT_COMPOSITE_2 = 248;
732 /** Key code constant: Component #1 key.
733 * Switches to component video input #1. */
734 public static final int KEYCODE_TV_INPUT_COMPONENT_1 = 249;
735 /** Key code constant: Component #2 key.
736 * Switches to component video input #2. */
737 public static final int KEYCODE_TV_INPUT_COMPONENT_2 = 250;
738 /** Key code constant: VGA #1 key.
739 * Switches to VGA (analog RGB) input #1. */
740 public static final int KEYCODE_TV_INPUT_VGA_1 = 251;
741 /** Key code constant: Audio description key.
742 * Toggles audio description off / on. */
743 public static final int KEYCODE_TV_AUDIO_DESCRIPTION = 252;
744 /** Key code constant: Audio description mixing volume up key.
745 * Louden audio description volume as compared with normal audio volume. */
746 public static final int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP = 253;
747 /** Key code constant: Audio description mixing volume down key.
748 * Lessen audio description volume as compared with normal audio volume. */
749 public static final int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN = 254;
750 /** Key code constant: Zoom mode key.
751 * Changes Zoom mode (Normal, Full, Zoom, Wide-zoom, etc.) */
752 public static final int KEYCODE_TV_ZOOM_MODE = 255;
753 /** Key code constant: Contents menu key.
754 * Goes to the title list. Corresponds to Contents Menu (0x0B) of CEC User Control
755 * Code */
756 public static final int KEYCODE_TV_CONTENTS_MENU = 256;
757 /** Key code constant: Media context menu key.
758 * Goes to the context menu of media contents. Corresponds to Media Context-sensitive
759 * Menu (0x11) of CEC User Control Code. */
760 public static final int KEYCODE_TV_MEDIA_CONTEXT_MENU = 257;
761 /** Key code constant: Timer programming key.
762 * Goes to the timer recording menu. Corresponds to Timer Programming (0x54) of
763 * CEC User Control Code. */
764 public static final int KEYCODE_TV_TIMER_PROGRAMMING = 258;
765 /** Key code constant: Help key. */
766 public static final int KEYCODE_HELP = 259;
767 /** Key code constant: Navigate to previous key.
768 * Goes backward by one item in an ordered collection of items. */
769 public static final int KEYCODE_NAVIGATE_PREVIOUS = 260;
770 /** Key code constant: Navigate to next key.
771 * Advances to the next item in an ordered collection of items. */
772 public static final int KEYCODE_NAVIGATE_NEXT = 261;
773 /** Key code constant: Navigate in key.
774 * Activates the item that currently has focus or expands to the next level of a navigation
775 * hierarchy. */
776 public static final int KEYCODE_NAVIGATE_IN = 262;
777 /** Key code constant: Navigate out key.
778 * Backs out one level of a navigation hierarchy or collapses the item that currently has
779 * focus. */
780 public static final int KEYCODE_NAVIGATE_OUT = 263;
781 /** Key code constant: Primary stem key for Wear
782 * Main power/reset button on watch. */
783 public static final int KEYCODE_STEM_PRIMARY = 264;
784 /** Key code constant: Generic stem key 1 for Wear */
785 public static final int KEYCODE_STEM_1 = 265;
786 /** Key code constant: Generic stem key 2 for Wear */
787 public static final int KEYCODE_STEM_2 = 266;
788 /** Key code constant: Generic stem key 3 for Wear */
789 public static final int KEYCODE_STEM_3 = 267;
790 /** Key code constant: Directional Pad Up-Left */
791 public static final int KEYCODE_DPAD_UP_LEFT = 268;
792 /** Key code constant: Directional Pad Down-Left */
793 public static final int KEYCODE_DPAD_DOWN_LEFT = 269;
794 /** Key code constant: Directional Pad Up-Right */
795 public static final int KEYCODE_DPAD_UP_RIGHT = 270;
796 /** Key code constant: Directional Pad Down-Right */
797 public static final int KEYCODE_DPAD_DOWN_RIGHT = 271;
798 /** Key code constant: Skip forward media key. */
799 public static final int KEYCODE_MEDIA_SKIP_FORWARD = 272;
800 /** Key code constant: Skip backward media key. */
801 public static final int KEYCODE_MEDIA_SKIP_BACKWARD = 273;
802 /** Key code constant: Step forward media key.
803 * Steps media forward, one frame at a time. */
804 public static final int KEYCODE_MEDIA_STEP_FORWARD = 274;
805 /** Key code constant: Step backward media key.
806 * Steps media backward, one frame at a time. */
807 public static final int KEYCODE_MEDIA_STEP_BACKWARD = 275;
808 /** Key code constant: put device to sleep unless a wakelock is held. */
809 public static final int KEYCODE_SOFT_SLEEP = 276;
810 /** Key code constant: Cut key. */
811 public static final int KEYCODE_CUT = 277;
812 /** Key code constant: Copy key. */
813 public static final int KEYCODE_COPY = 278;
814 /** Key code constant: Paste key. */
815 public static final int KEYCODE_PASTE = 279;
816 /** Key code constant: Consumed by the system for navigation up */
817 public static final int KEYCODE_SYSTEM_NAVIGATION_UP = 280;
818 /** Key code constant: Consumed by the system for navigation down */
819 public static final int KEYCODE_SYSTEM_NAVIGATION_DOWN = 281;
820 /** Key code constant: Consumed by the system for navigation left*/
821 public static final int KEYCODE_SYSTEM_NAVIGATION_LEFT = 282;
822 /** Key code constant: Consumed by the system for navigation right */
823 public static final int KEYCODE_SYSTEM_NAVIGATION_RIGHT = 283;
824 /** Key code constant: Show all apps */
825 public static final int KEYCODE_ALL_APPS = 284;
826 /** Key code constant: Refresh key. */
827 public static final int KEYCODE_REFRESH = 285;
828 /** Key code constant: Thumbs up key. Apps can use this to let user upvote content. */
829 public static final int KEYCODE_THUMBS_UP = 286;
830 /** Key code constant: Thumbs down key. Apps can use this to let user downvote content. */
831 public static final int KEYCODE_THUMBS_DOWN = 287;
832 /**
833 * Key code constant: Used to switch current {@link android.accounts.Account} that is
834 * consuming content. May be consumed by system to set account globally.
835 */
836 public static final int KEYCODE_PROFILE_SWITCH = 288;
837 /** Key code constant: Video Application key #1. */
838 public static final int KEYCODE_VIDEO_APP_1 = 289;
839 /** Key code constant: Video Application key #2. */
840 public static final int KEYCODE_VIDEO_APP_2 = 290;
841 /** Key code constant: Video Application key #3. */
842 public static final int KEYCODE_VIDEO_APP_3 = 291;
843 /** Key code constant: Video Application key #4. */
844 public static final int KEYCODE_VIDEO_APP_4 = 292;
845 /** Key code constant: Video Application key #5. */
846 public static final int KEYCODE_VIDEO_APP_5 = 293;
847 /** Key code constant: Video Application key #6. */
848 public static final int KEYCODE_VIDEO_APP_6 = 294;
849 /** Key code constant: Video Application key #7. */
850 public static final int KEYCODE_VIDEO_APP_7 = 295;
851 /** Key code constant: Video Application key #8. */
852 public static final int KEYCODE_VIDEO_APP_8 = 296;
853 /** Key code constant: Featured Application key #1. */
854 public static final int KEYCODE_FEATURED_APP_1 = 297;
855 /** Key code constant: Featured Application key #2. */
856 public static final int KEYCODE_FEATURED_APP_2 = 298;
857 /** Key code constant: Featured Application key #3. */
858 public static final int KEYCODE_FEATURED_APP_3 = 299;
859 /** Key code constant: Featured Application key #4. */
860 public static final int KEYCODE_FEATURED_APP_4 = 300;
861 /** Key code constant: Demo Application key #1. */
862 public static final int KEYCODE_DEMO_APP_1 = 301;
863 /** Key code constant: Demo Application key #2. */
864 public static final int KEYCODE_DEMO_APP_2 = 302;
865 /** Key code constant: Demo Application key #3. */
866 public static final int KEYCODE_DEMO_APP_3 = 303;
867 /** Key code constant: Demo Application key #4. */
868 public static final int KEYCODE_DEMO_APP_4 = 304;
869
870 /**
871 * Integer value of the last KEYCODE. Increases as new keycodes are added to KeyEvent.
872 * @hide
873 */
874 @TestApi
875 public static final int LAST_KEYCODE = KEYCODE_DEMO_APP_4;
876
877 // NOTE: If you add a new keycode here you must also add it to:
878 // isSystem()
879 // isWakeKey()
880 // frameworks/native/include/android/keycodes.h
881 // frameworks/native/include/input/InputEventLabels.h
882 // frameworks/base/core/res/res/values/attrs.xml
883 // emulator?
884 // LAST_KEYCODE
885 //
886 // Also Android currently does not reserve code ranges for vendor-
887 // specific key codes. If you have new key codes to have, you
888 // MUST contribute a patch to the open source project to define
889 // those new codes. This is intended to maintain a consistent
890 // set of key code definitions across all Android devices.
891
892 // Symbolic names of all metakeys in bit order from least significant to most significant.
893 // Accordingly there are exactly 32 values in this table.
894 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
895 private static final String[] META_SYMBOLIC_NAMES = new String[] {
896 "META_SHIFT_ON",
897 "META_ALT_ON",
898 "META_SYM_ON",
899 "META_FUNCTION_ON",
900 "META_ALT_LEFT_ON",
901 "META_ALT_RIGHT_ON",
902 "META_SHIFT_LEFT_ON",
903 "META_SHIFT_RIGHT_ON",
904 "META_CAP_LOCKED",
905 "META_ALT_LOCKED",
906 "META_SYM_LOCKED",
907 "0x00000800",
908 "META_CTRL_ON",
909 "META_CTRL_LEFT_ON",
910 "META_CTRL_RIGHT_ON",
911 "0x00008000",
912 "META_META_ON",
913 "META_META_LEFT_ON",
914 "META_META_RIGHT_ON",
915 "0x00080000",
916 "META_CAPS_LOCK_ON",
917 "META_NUM_LOCK_ON",
918 "META_SCROLL_LOCK_ON",
919 "0x00800000",
920 "0x01000000",
921 "0x02000000",
922 "0x04000000",
923 "0x08000000",
924 "0x10000000",
925 "0x20000000",
926 "0x40000000",
927 "0x80000000",
928 };
929
930 private static final String LABEL_PREFIX = "KEYCODE_";
931
932 /**
933 * @deprecated There are now more than MAX_KEYCODE keycodes.
934 * Use {@link #getMaxKeyCode()} instead.
935 */
936 @Deprecated
937 public static final int MAX_KEYCODE = 84;
938
939 /**
940 * {@link #getAction} value: the key has been pressed down.
941 */
942 public static final int ACTION_DOWN = 0;
943 /**
944 * {@link #getAction} value: the key has been released.
945 */
946 public static final int ACTION_UP = 1;
947 /**
948 * @deprecated No longer used by the input system.
949 * {@link #getAction} value: multiple duplicate key events have
950 * occurred in a row, or a complex string is being delivered. If the
951 * key code is not {@link #KEYCODE_UNKNOWN} then the
952 * {@link #getRepeatCount()} method returns the number of times
953 * the given key code should be executed.
954 * Otherwise, if the key code is {@link #KEYCODE_UNKNOWN}, then
955 * this is a sequence of characters as returned by {@link #getCharacters}.
956 */
957 @Deprecated
958 public static final int ACTION_MULTIPLE = 2;
959
960 /**
961 * SHIFT key locked in CAPS mode.
962 * Reserved for use by {@link MetaKeyKeyListener} for a published constant in its API.
963 * @hide
964 */
965 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
966 public static final int META_CAP_LOCKED = 0x100;
967
968 /**
969 * ALT key locked.
970 * Reserved for use by {@link MetaKeyKeyListener} for a published constant in its API.
971 * @hide
972 */
973 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
974 public static final int META_ALT_LOCKED = 0x200;
975
976 /**
977 * SYM key locked.
978 * Reserved for use by {@link MetaKeyKeyListener} for a published constant in its API.
979 * @hide
980 */
981 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
982 public static final int META_SYM_LOCKED = 0x400;
983
984 /**
985 * Text is in selection mode.
986 * Reserved for use by {@link MetaKeyKeyListener} for a private unpublished constant
987 * in its API that is currently being retained for legacy reasons.
988 * @hide
989 */
990 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
991 public static final int META_SELECTING = 0x800;
992
993 /**
994 * <p>This mask is used to check whether one of the ALT meta keys is pressed.</p>
995 *
996 * @see #isAltPressed()
997 * @see #getMetaState()
998 * @see #KEYCODE_ALT_LEFT
999 * @see #KEYCODE_ALT_RIGHT
1000 */
1001 public static final int META_ALT_ON = 0x02;
1002
1003 /**
1004 * <p>This mask is used to check whether the left ALT meta key is pressed.</p>
1005 *
1006 * @see #isAltPressed()
1007 * @see #getMetaState()
1008 * @see #KEYCODE_ALT_LEFT
1009 */
1010 public static final int META_ALT_LEFT_ON = 0x10;
1011
1012 /**
1013 * <p>This mask is used to check whether the right the ALT meta key is pressed.</p>
1014 *
1015 * @see #isAltPressed()
1016 * @see #getMetaState()
1017 * @see #KEYCODE_ALT_RIGHT
1018 */
1019 public static final int META_ALT_RIGHT_ON = 0x20;
1020
1021 /**
1022 * <p>This mask is used to check whether one of the SHIFT meta keys is pressed.</p>
1023 *
1024 * @see #isShiftPressed()
1025 * @see #getMetaState()
1026 * @see #KEYCODE_SHIFT_LEFT
1027 * @see #KEYCODE_SHIFT_RIGHT
1028 */
1029 public static final int META_SHIFT_ON = 0x1;
1030
1031 /**
1032 * <p>This mask is used to check whether the left SHIFT meta key is pressed.</p>
1033 *
1034 * @see #isShiftPressed()
1035 * @see #getMetaState()
1036 * @see #KEYCODE_SHIFT_LEFT
1037 */
1038 public static final int META_SHIFT_LEFT_ON = 0x40;
1039
1040 /**
1041 * <p>This mask is used to check whether the right SHIFT meta key is pressed.</p>
1042 *
1043 * @see #isShiftPressed()
1044 * @see #getMetaState()
1045 * @see #KEYCODE_SHIFT_RIGHT
1046 */
1047 public static final int META_SHIFT_RIGHT_ON = 0x80;
1048
1049 /**
1050 * <p>This mask is used to check whether the SYM meta key is pressed.</p>
1051 *
1052 * @see #isSymPressed()
1053 * @see #getMetaState()
1054 */
1055 public static final int META_SYM_ON = 0x4;
1056
1057 /**
1058 * <p>This mask is used to check whether the FUNCTION meta key is pressed.</p>
1059 *
1060 * @see #isFunctionPressed()
1061 * @see #getMetaState()
1062 */
1063 public static final int META_FUNCTION_ON = 0x8;
1064
1065 /**
1066 * <p>This mask is used to check whether one of the CTRL meta keys is pressed.</p>
1067 *
1068 * @see #isCtrlPressed()
1069 * @see #getMetaState()
1070 * @see #KEYCODE_CTRL_LEFT
1071 * @see #KEYCODE_CTRL_RIGHT
1072 */
1073 public static final int META_CTRL_ON = 0x1000;
1074
1075 /**
1076 * <p>This mask is used to check whether the left CTRL meta key is pressed.</p>
1077 *
1078 * @see #isCtrlPressed()
1079 * @see #getMetaState()
1080 * @see #KEYCODE_CTRL_LEFT
1081 */
1082 public static final int META_CTRL_LEFT_ON = 0x2000;
1083
1084 /**
1085 * <p>This mask is used to check whether the right CTRL meta key is pressed.</p>
1086 *
1087 * @see #isCtrlPressed()
1088 * @see #getMetaState()
1089 * @see #KEYCODE_CTRL_RIGHT
1090 */
1091 public static final int META_CTRL_RIGHT_ON = 0x4000;
1092
1093 /**
1094 * <p>This mask is used to check whether one of the META meta keys is pressed.</p>
1095 *
1096 * @see #isMetaPressed()
1097 * @see #getMetaState()
1098 * @see #KEYCODE_META_LEFT
1099 * @see #KEYCODE_META_RIGHT
1100 */
1101 public static final int META_META_ON = 0x10000;
1102
1103 /**
1104 * <p>This mask is used to check whether the left META meta key is pressed.</p>
1105 *
1106 * @see #isMetaPressed()
1107 * @see #getMetaState()
1108 * @see #KEYCODE_META_LEFT
1109 */
1110 public static final int META_META_LEFT_ON = 0x20000;
1111
1112 /**
1113 * <p>This mask is used to check whether the right META meta key is pressed.</p>
1114 *
1115 * @see #isMetaPressed()
1116 * @see #getMetaState()
1117 * @see #KEYCODE_META_RIGHT
1118 */
1119 public static final int META_META_RIGHT_ON = 0x40000;
1120
1121 /**
1122 * <p>This mask is used to check whether the CAPS LOCK meta key is on.</p>
1123 *
1124 * @see #isCapsLockOn()
1125 * @see #getMetaState()
1126 * @see #KEYCODE_CAPS_LOCK
1127 */
1128 public static final int META_CAPS_LOCK_ON = 0x100000;
1129
1130 /**
1131 * <p>This mask is used to check whether the NUM LOCK meta key is on.</p>
1132 *
1133 * @see #isNumLockOn()
1134 * @see #getMetaState()
1135 * @see #KEYCODE_NUM_LOCK
1136 */
1137 public static final int META_NUM_LOCK_ON = 0x200000;
1138
1139 /**
1140 * <p>This mask is used to check whether the SCROLL LOCK meta key is on.</p>
1141 *
1142 * @see #isScrollLockOn()
1143 * @see #getMetaState()
1144 * @see #KEYCODE_SCROLL_LOCK
1145 */
1146 public static final int META_SCROLL_LOCK_ON = 0x400000;
1147
1148 /**
1149 * This mask is a combination of {@link #META_SHIFT_ON}, {@link #META_SHIFT_LEFT_ON}
1150 * and {@link #META_SHIFT_RIGHT_ON}.
1151 */
1152 public static final int META_SHIFT_MASK = META_SHIFT_ON
1153 | META_SHIFT_LEFT_ON | META_SHIFT_RIGHT_ON;
1154
1155 /**
1156 * This mask is a combination of {@link #META_ALT_ON}, {@link #META_ALT_LEFT_ON}
1157 * and {@link #META_ALT_RIGHT_ON}.
1158 */
1159 public static final int META_ALT_MASK = META_ALT_ON
1160 | META_ALT_LEFT_ON | META_ALT_RIGHT_ON;
1161
1162 /**
1163 * This mask is a combination of {@link #META_CTRL_ON}, {@link #META_CTRL_LEFT_ON}
1164 * and {@link #META_CTRL_RIGHT_ON}.
1165 */
1166 public static final int META_CTRL_MASK = META_CTRL_ON
1167 | META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON;
1168
1169 /**
1170 * This mask is a combination of {@link #META_META_ON}, {@link #META_META_LEFT_ON}
1171 * and {@link #META_META_RIGHT_ON}.
1172 */
1173 public static final int META_META_MASK = META_META_ON
1174 | META_META_LEFT_ON | META_META_RIGHT_ON;
1175
1176 /**
1177 * This mask is set if the device woke because of this key event.
1178 *
1179 * @deprecated This flag will never be set by the system since the system
1180 * consumes all wake keys itself.
1181 */
1182 @Deprecated
1183 public static final int FLAG_WOKE_HERE = 0x1;
1184
1185 /**
1186 * This mask is set if the key event was generated by a software keyboard.
1187 */
1188 public static final int FLAG_SOFT_KEYBOARD = 0x2;
1189
1190 /**
1191 * This mask is set if we don't want the key event to cause us to leave
1192 * touch mode.
1193 */
1194 public static final int FLAG_KEEP_TOUCH_MODE = 0x4;
1195
1196 /**
1197 * This mask is set if an event was known to come from a trusted part
1198 * of the system. That is, the event is known to come from the user,
1199 * and could not have been spoofed by a third party component.
1200 */
1201 public static final int FLAG_FROM_SYSTEM = 0x8;
1202
1203 /**
1204 * This mask is used for compatibility, to identify enter keys that are
1205 * coming from an IME whose enter key has been auto-labelled "next" or
1206 * "done". This allows TextView to dispatch these as normal enter keys
1207 * for old applications, but still do the appropriate action when
1208 * receiving them.
1209 */
1210 public static final int FLAG_EDITOR_ACTION = 0x10;
1211
1212 /**
1213 * When associated with up key events, this indicates that the key press
1214 * has been canceled. Typically this is used with virtual touch screen
1215 * keys, where the user can slide from the virtual key area on to the
1216 * display: in that case, the application will receive a canceled up
1217 * event and should not perform the action normally associated with the
1218 * key. Note that for this to work, the application can not perform an
1219 * action for a key until it receives an up or the long press timeout has
1220 * expired.
1221 */
1222 public static final int FLAG_CANCELED = 0x20;
1223
1224 /**
1225 * This key event was generated by a virtual (on-screen) hard key area.
1226 * Typically this is an area of the touchscreen, outside of the regular
1227 * display, dedicated to "hardware" buttons.
1228 */
1229 public static final int FLAG_VIRTUAL_HARD_KEY = 0x40;
1230
1231 /**
1232 * This flag is set for the first key repeat that occurs after the
1233 * long press timeout.
1234 */
1235 public static final int FLAG_LONG_PRESS = 0x80;
1236
1237 /**
1238 * Set when a key event has {@link #FLAG_CANCELED} set because a long
1239 * press action was executed while it was down.
1240 */
1241 public static final int FLAG_CANCELED_LONG_PRESS = 0x100;
1242
1243 /**
1244 * Set for {@link #ACTION_UP} when this event's key code is still being
1245 * tracked from its initial down. That is, somebody requested that tracking
1246 * started on the key down and a long press has not caused
1247 * the tracking to be canceled.
1248 */
1249 public static final int FLAG_TRACKING = 0x200;
1250
1251 /**
1252 * Set when a key event has been synthesized to implement default behavior
1253 * for an event that the application did not handle.
1254 * Fallback key events are generated by unhandled trackball motions
1255 * (to emulate a directional keypad) and by certain unhandled key presses
1256 * that are declared in the key map (such as special function numeric keypad
1257 * keys when numlock is off).
1258 */
1259 public static final int FLAG_FALLBACK = 0x400;
1260
1261 /**
1262 * This flag indicates that this event was modified by or generated from an accessibility
1263 * service. Value = 0x800
1264 * @hide
1265 */
1266 @TestApi
1267 public static final int FLAG_IS_ACCESSIBILITY_EVENT = INPUT_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
1268
1269 /**
1270 * Signifies that the key is being predispatched.
1271 * @hide
1272 */
1273 public static final int FLAG_PREDISPATCH = 0x20000000;
1274
1275 /**
1276 * Private control to determine when an app is tracking a key sequence.
1277 * @hide
1278 */
1279 public static final int FLAG_START_TRACKING = 0x40000000;
1280
1281 /**
1282 * Private flag that indicates when the system has detected that this key event
1283 * may be inconsistent with respect to the sequence of previously delivered key events,
1284 * such as when a key up event is sent but the key was not down.
1285 *
1286 * @hide
1287 * @see #isTainted
1288 * @see #setTainted
1289 */
1290 public static final int FLAG_TAINTED = 0x80000000;
1291
1292 /**
1293 * Returns the maximum keycode.
1294 */
1295 public static int getMaxKeyCode() {
1296 return LAST_KEYCODE;
1297 }
1298
1299 /**
1300 * Get the character that is produced by putting accent on the character
1301 * c.
1302 * For example, getDeadChar('`', 'e') returns &egrave;.
1303 */
1304 public static int getDeadChar(int accent, int c) {
1305 return KeyCharacterMap.getDeadChar(accent, c);
1306 }
1307
1308 static final boolean DEBUG = false;
1309 static final String TAG = "KeyEvent";
1310
1311 private static final int MAX_RECYCLED = 10;
1312 private static final Object gRecyclerLock = new Object();
1313 private static int gRecyclerUsed;
1314 private static KeyEvent gRecyclerTop;
1315
1316 private KeyEvent mNext;
1317
1318 private int mId;
1319 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1320 private int mDeviceId;
1321 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
1322 private int mSource;
1323 private int mDisplayId;
1324 private @Nullable byte[] mHmac;
1325 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1326 private int mMetaState;
1327 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1328 private int mAction;
1329 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1330 private int mKeyCode;
1331 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1332 private int mScanCode;
1333 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1334 private int mRepeatCount;
1335 @UnsupportedAppUsage
1336 private int mFlags;
1337 /**
1338 * The time when the key initially was pressed, in nanoseconds. Only millisecond precision is
1339 * exposed as public api, so this must always be converted to / from milliseconds when used.
1340 */
1341 private long mDownTime;
1342 /**
1343 * The time when the current key event occurred. If mAction is ACTION_DOWN, then this is equal
1344 * to mDownTime. Only millisecond precision is exposed as public api, so this must always be
1345 * converted to / from milliseconds when used.
1346 */
1347 private long mEventTime;
1348 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1349 private String mCharacters;
1350
1351 public interface Callback {
1352 /**
1353 * Called when a key down event has occurred. If you return true,
1354 * you can first call {@link KeyEvent#startTracking()
1355 * KeyEvent.startTracking()} to have the framework track the event
1356 * through its {@link #onKeyUp(int, KeyEvent)} and also call your
1357 * {@link #onKeyLongPress(int, KeyEvent)} if it occurs.
1358 *
1359 * @param keyCode The value in event.getKeyCode().
1360 * @param event Description of the key event.
1361 *
1362 * @return If you handled the event, return true. If you want to allow
1363 * the event to be handled by the next receiver, return false.
1364 */
1365 boolean onKeyDown(int keyCode, KeyEvent event);
1366
1367 /**
1368 * Called when a long press has occurred. If you return true,
1369 * the final key up will have {@link KeyEvent#FLAG_CANCELED} and
1370 * {@link KeyEvent#FLAG_CANCELED_LONG_PRESS} set. Note that in
1371 * order to receive this callback, someone in the event change
1372 * <em>must</em> return true from {@link #onKeyDown} <em>and</em>
1373 * call {@link KeyEvent#startTracking()} on the event.
1374 *
1375 * @param keyCode The value in event.getKeyCode().
1376 * @param event Description of the key event.
1377 *
1378 * @return If you handled the event, return true. If you want to allow
1379 * the event to be handled by the next receiver, return false.
1380 */
1381 boolean onKeyLongPress(int keyCode, KeyEvent event);
1382
1383 /**
1384 * Called when a key up event has occurred.
1385 *
1386 * @param keyCode The value in event.getKeyCode().
1387 * @param event Description of the key event.
1388 *
1389 * @return If you handled the event, return true. If you want to allow
1390 * the event to be handled by the next receiver, return false.
1391 */
1392 boolean onKeyUp(int keyCode, KeyEvent event);
1393
1394 /**
1395 * Called when a user's interaction with an analog control, such as
1396 * flinging a trackball, generates simulated down/up events for the same
1397 * key multiple times in quick succession.
1398 *
1399 * @param keyCode The value in event.getKeyCode().
1400 * @param count Number of pairs as returned by event.getRepeatCount().
1401 * @param event Description of the key event.
1402 *
1403 * @return If you handled the event, return true. If you want to allow
1404 * the event to be handled by the next receiver, return false.
1405 */
1406 boolean onKeyMultiple(int keyCode, int count, KeyEvent event);
1407 }
1408
1409 private static native String nativeKeyCodeToString(int keyCode);
1410 private static native int nativeKeyCodeFromString(String keyCode);
1411 private static native int nativeNextId();
1412
1413 private KeyEvent() {}
1414
1415 /**
1416 * Create a new key event.
1417 *
1418 * @param action Action code: either {@link #ACTION_DOWN},
1419 * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1420 * @param code The key code.
1421 */
1422 public KeyEvent(int action, int code) {
1423 mId = nativeNextId();
1424 mAction = action;
1425 mKeyCode = code;
1426 mRepeatCount = 0;
1427 mDeviceId = KeyCharacterMap.VIRTUAL_KEYBOARD;
1428 }
1429
1430 /**
1431 * Create a new key event.
1432 *
1433 * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1434 * at which this key code originally went down.
1435 * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1436 * at which this event happened.
1437 * @param action Action code: either {@link #ACTION_DOWN},
1438 * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1439 * @param code The key code.
1440 * @param repeat A repeat count for down events (> 0 if this is after the
1441 * initial down) or event count for multiple events.
1442 */
1443 public KeyEvent(long downTime, long eventTime, int action,
1444 int code, int repeat) {
1445 mId = nativeNextId();
1446 mDownTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
1447 mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1448 mAction = action;
1449 mKeyCode = code;
1450 mRepeatCount = repeat;
1451 mDeviceId = KeyCharacterMap.VIRTUAL_KEYBOARD;
1452 }
1453
1454 /**
1455 * Create a new key event.
1456 *
1457 * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1458 * at which this key code originally went down.
1459 * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1460 * at which this event happened.
1461 * @param action Action code: either {@link #ACTION_DOWN},
1462 * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1463 * @param code The key code.
1464 * @param repeat A repeat count for down events (> 0 if this is after the
1465 * initial down) or event count for multiple events.
1466 * @param metaState Flags indicating which meta keys are currently pressed.
1467 */
1468 public KeyEvent(long downTime, long eventTime, int action,
1469 int code, int repeat, int metaState) {
1470 mId = nativeNextId();
1471 mDownTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
1472 mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1473 mAction = action;
1474 mKeyCode = code;
1475 mRepeatCount = repeat;
1476 mMetaState = metaState;
1477 mDeviceId = KeyCharacterMap.VIRTUAL_KEYBOARD;
1478 }
1479
1480 /**
1481 * Create a new key event.
1482 *
1483 * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1484 * at which this key code originally went down.
1485 * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1486 * at which this event happened.
1487 * @param action Action code: either {@link #ACTION_DOWN},
1488 * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1489 * @param code The key code.
1490 * @param repeat A repeat count for down events (> 0 if this is after the
1491 * initial down) or event count for multiple events.
1492 * @param metaState Flags indicating which meta keys are currently pressed.
1493 * @param deviceId The device ID that generated the key event.
1494 * @param scancode Raw device scan code of the event.
1495 */
1496 public KeyEvent(long downTime, long eventTime, int action,
1497 int code, int repeat, int metaState,
1498 int deviceId, int scancode) {
1499 mId = nativeNextId();
1500 mDownTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
1501 mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1502 mAction = action;
1503 mKeyCode = code;
1504 mRepeatCount = repeat;
1505 mMetaState = metaState;
1506 mDeviceId = deviceId;
1507 mScanCode = scancode;
1508 }
1509
1510 /**
1511 * Create a new key event.
1512 *
1513 * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1514 * at which this key code originally went down.
1515 * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1516 * at which this event happened.
1517 * @param action Action code: either {@link #ACTION_DOWN},
1518 * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1519 * @param code The key code.
1520 * @param repeat A repeat count for down events (> 0 if this is after the
1521 * initial down) or event count for multiple events.
1522 * @param metaState Flags indicating which meta keys are currently pressed.
1523 * @param deviceId The device ID that generated the key event.
1524 * @param scancode Raw device scan code of the event.
1525 * @param flags The flags for this key event
1526 */
1527 public KeyEvent(long downTime, long eventTime, int action,
1528 int code, int repeat, int metaState,
1529 int deviceId, int scancode, int flags) {
1530 mId = nativeNextId();
1531 mDownTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
1532 mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1533 mAction = action;
1534 mKeyCode = code;
1535 mRepeatCount = repeat;
1536 mMetaState = metaState;
1537 mDeviceId = deviceId;
1538 mScanCode = scancode;
1539 mFlags = flags;
1540 }
1541
1542 /**
1543 * Create a new key event.
1544 *
1545 * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1546 * at which this key code originally went down.
1547 * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1548 * at which this event happened.
1549 * @param action Action code: either {@link #ACTION_DOWN},
1550 * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1551 * @param code The key code.
1552 * @param repeat A repeat count for down events (> 0 if this is after the
1553 * initial down) or event count for multiple events.
1554 * @param metaState Flags indicating which meta keys are currently pressed.
1555 * @param deviceId The device ID that generated the key event.
1556 * @param scancode Raw device scan code of the event.
1557 * @param flags The flags for this key event
1558 * @param source The input source such as {@link InputDevice#SOURCE_KEYBOARD}.
1559 */
1560 public KeyEvent(long downTime, long eventTime, int action,
1561 int code, int repeat, int metaState,
1562 int deviceId, int scancode, int flags, int source) {
1563 mId = nativeNextId();
1564 mDownTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
1565 mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1566 mAction = action;
1567 mKeyCode = code;
1568 mRepeatCount = repeat;
1569 mMetaState = metaState;
1570 mDeviceId = deviceId;
1571 mScanCode = scancode;
1572 mFlags = flags;
1573 mSource = source;
1574 mDisplayId = INVALID_DISPLAY;
1575 }
1576
1577 /**
1578 * Create a new key event for a string of characters. The key code,
1579 * action, repeat count and source will automatically be set to
1580 * {@link #KEYCODE_UNKNOWN}, {@link #ACTION_MULTIPLE}, 0, and
1581 * {@link InputDevice#SOURCE_KEYBOARD} for you.
1582 *
1583 * @param time The time (in {@link android.os.SystemClock#uptimeMillis})
1584 * at which this event occured.
1585 * @param characters The string of characters.
1586 * @param deviceId The device ID that generated the key event.
1587 * @param flags The flags for this key event
1588 */
1589 public KeyEvent(long time, String characters, int deviceId, int flags) {
1590 mId = nativeNextId();
1591 mDownTime = TimeUnit.NANOSECONDS.convert(time, TimeUnit.MILLISECONDS);
1592 mEventTime = TimeUnit.NANOSECONDS.convert(time, TimeUnit.MILLISECONDS);
1593 mCharacters = characters;
1594 mAction = ACTION_MULTIPLE;
1595 mKeyCode = KEYCODE_UNKNOWN;
1596 mRepeatCount = 0;
1597 mDeviceId = deviceId;
1598 mFlags = flags;
1599 mSource = InputDevice.SOURCE_KEYBOARD;
1600 mDisplayId = INVALID_DISPLAY;
1601 }
1602
1603 /**
1604 * Make an exact copy of an existing key event.
1605 */
1606 public KeyEvent(KeyEvent origEvent) {
1607 mId = origEvent.mId;
1608 mDownTime = origEvent.mDownTime;
1609 mEventTime = origEvent.mEventTime;
1610 mAction = origEvent.mAction;
1611 mKeyCode = origEvent.mKeyCode;
1612 mRepeatCount = origEvent.mRepeatCount;
1613 mMetaState = origEvent.mMetaState;
1614 mDeviceId = origEvent.mDeviceId;
1615 mSource = origEvent.mSource;
1616 mDisplayId = origEvent.mDisplayId;
1617 mHmac = origEvent.mHmac == null ? null : origEvent.mHmac.clone();
1618 mScanCode = origEvent.mScanCode;
1619 mFlags = origEvent.mFlags;
1620 mCharacters = origEvent.mCharacters;
1621 }
1622
1623 /**
1624 * Copy an existing key event, modifying its time and repeat count.
1625 *
1626 * @deprecated Use {@link #changeTimeRepeat(KeyEvent, long, int)}
1627 * instead.
1628 *
1629 * @param origEvent The existing event to be copied.
1630 * @param eventTime The new event time
1631 * (in {@link android.os.SystemClock#uptimeMillis}) of the event.
1632 * @param newRepeat The new repeat count of the event.
1633 */
1634 @Deprecated
1635 public KeyEvent(KeyEvent origEvent, long eventTime, int newRepeat) {
1636 mId = nativeNextId(); // Not an exact copy so assign a new ID.
1637 mDownTime = origEvent.mDownTime;
1638 mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1639 mAction = origEvent.mAction;
1640 mKeyCode = origEvent.mKeyCode;
1641 mRepeatCount = newRepeat;
1642 mMetaState = origEvent.mMetaState;
1643 mDeviceId = origEvent.mDeviceId;
1644 mSource = origEvent.mSource;
1645 mDisplayId = origEvent.mDisplayId;
1646 mHmac = null; // Don't copy HMAC, it will be invalid because eventTime is changing
1647 mScanCode = origEvent.mScanCode;
1648 mFlags = origEvent.mFlags;
1649 mCharacters = origEvent.mCharacters;
1650 }
1651
1652 private static KeyEvent obtain() {
1653 final KeyEvent ev;
1654 synchronized (gRecyclerLock) {
1655 ev = gRecyclerTop;
1656 if (ev == null) {
1657 return new KeyEvent();
1658 }
1659 gRecyclerTop = ev.mNext;
1660 gRecyclerUsed -= 1;
1661 }
1662 ev.mNext = null;
1663 ev.prepareForReuse();
1664 return ev;
1665 }
1666
1667 /**
1668 * Obtains a (potentially recycled) key event. Used by native code to create a Java object.
1669 *
1670 * @hide
1671 */
1672 private static KeyEvent obtain(int id, long downTimeNanos, long eventTimeNanos, int action,
1673 int code, int repeat, int metaState,
1674 int deviceId, int scancode, int flags, int source, int displayId, @Nullable byte[] hmac,
1675 String characters) {
1676 KeyEvent ev = obtain();
1677 ev.mId = id;
1678 ev.mDownTime = downTimeNanos;
1679 ev.mEventTime = eventTimeNanos;
1680 ev.mAction = action;
1681 ev.mKeyCode = code;
1682 ev.mRepeatCount = repeat;
1683 ev.mMetaState = metaState;
1684 ev.mDeviceId = deviceId;
1685 ev.mScanCode = scancode;
1686 ev.mFlags = flags;
1687 ev.mSource = source;
1688 ev.mDisplayId = displayId;
1689 ev.mHmac = hmac;
1690 ev.mCharacters = characters;
1691 return ev;
1692 }
1693
1694 /**
1695 * Obtains a (potentially recycled) key event.
1696 *
1697 * @hide
1698 */
1699 public static KeyEvent obtain(long downTime, long eventTime, int action,
1700 int code, int repeat, int metaState,
1701 int deviceId, int scanCode, int flags, int source, int displayId, String characters) {
1702 downTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
1703 eventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1704 return obtain(nativeNextId(), downTime, eventTime, action, code, repeat, metaState,
1705 deviceId, scanCode, flags, source, displayId, null /* hmac */, characters);
1706 }
1707
1708 /**
1709 * Obtains a (potentially recycled) key event.
1710 *
1711 * @hide
1712 */
1713 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1714 public static KeyEvent obtain(long downTime, long eventTime, int action,
1715 int code, int repeat, int metaState,
1716 int deviceId, int scancode, int flags, int source, String characters) {
1717 // Do not convert downTime and eventTime here. We are calling the obtain method above,
1718 // which will do the conversion. Just specify INVALID_DISPLAY and forward the request.
1719 return obtain(downTime, eventTime, action, code, repeat, metaState, deviceId, scancode,
1720 flags, source, INVALID_DISPLAY, characters);
1721 }
1722
1723 /**
1724
1725 /**
1726 * Obtains a (potentially recycled) copy of another key event.
1727 *
1728 * @hide
1729 */
1730 public static KeyEvent obtain(KeyEvent other) {
1731 KeyEvent ev = obtain();
1732 ev.mId = other.mId;
1733 ev.mDownTime = other.mDownTime;
1734 ev.mEventTime = other.mEventTime;
1735 ev.mAction = other.mAction;
1736 ev.mKeyCode = other.mKeyCode;
1737 ev.mRepeatCount = other.mRepeatCount;
1738 ev.mMetaState = other.mMetaState;
1739 ev.mDeviceId = other.mDeviceId;
1740 ev.mScanCode = other.mScanCode;
1741 ev.mFlags = other.mFlags;
1742 ev.mSource = other.mSource;
1743 ev.mDisplayId = other.mDisplayId;
1744 ev.mHmac = other.mHmac == null ? null : other.mHmac.clone();
1745 ev.mCharacters = other.mCharacters;
1746 return ev;
1747 }
1748
1749 /** @hide */
1750 @Override
1751 public KeyEvent copy() {
1752 return obtain(this);
1753 }
1754
1755 /**
1756 * Recycles a key event.
1757 * Key events should only be recycled if they are owned by the system since user
1758 * code expects them to be essentially immutable, "tracking" notwithstanding.
1759 *
1760 * @hide
1761 */
1762 @Override
1763 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
1764 public final void recycle() {
1765 super.recycle();
1766 mCharacters = null;
1767
1768 synchronized (gRecyclerLock) {
1769 if (gRecyclerUsed < MAX_RECYCLED) {
1770 gRecyclerUsed++;
1771 mNext = gRecyclerTop;
1772 gRecyclerTop = this;
1773 }
1774 }
1775 }
1776
1777 /** @hide */
1778 @Override
1779 public final void recycleIfNeededAfterDispatch() {
1780 // Do nothing.
1781 }
1782
1783 /** @hide */
1784 @Override
1785 public int getId() {
1786 return mId;
1787 }
1788
1789 /**
1790 * Create a new key event that is the same as the given one, but whose
1791 * event time and repeat count are replaced with the given value.
1792 *
1793 * @param event The existing event to be copied. This is not modified.
1794 * @param eventTime The new event time
1795 * (in {@link android.os.SystemClock#uptimeMillis}) of the event.
1796 * @param newRepeat The new repeat count of the event.
1797 */
1798 public static KeyEvent changeTimeRepeat(KeyEvent event, long eventTime,
1799 int newRepeat) {
1800 return new KeyEvent(event, eventTime, newRepeat);
1801 }
1802
1803 /**
1804 * Create a new key event that is the same as the given one, but whose
1805 * event time and repeat count are replaced with the given value.
1806 *
1807 * @param event The existing event to be copied. This is not modified.
1808 * @param eventTime The new event time
1809 * (in {@link android.os.SystemClock#uptimeMillis}) of the event.
1810 * @param newRepeat The new repeat count of the event.
1811 * @param newFlags New flags for the event, replacing the entire value
1812 * in the original event.
1813 */
1814 public static KeyEvent changeTimeRepeat(KeyEvent event, long eventTime,
1815 int newRepeat, int newFlags) {
1816 KeyEvent ret = new KeyEvent(event);
1817 ret.mId = nativeNextId(); // Not an exact copy so assign a new ID.
1818 ret.mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1819 ret.mRepeatCount = newRepeat;
1820 ret.mFlags = newFlags;
1821 return ret;
1822 }
1823
1824 /**
1825 * Copy an existing key event, modifying its action.
1826 *
1827 * @param origEvent The existing event to be copied.
1828 * @param action The new action code of the event.
1829 */
1830 private KeyEvent(KeyEvent origEvent, int action) {
1831 mId = nativeNextId(); // Not an exact copy so assign a new ID.
1832 mDownTime = origEvent.mDownTime;
1833 mEventTime = origEvent.mEventTime;
1834 mAction = action;
1835 mKeyCode = origEvent.mKeyCode;
1836 mRepeatCount = origEvent.mRepeatCount;
1837 mMetaState = origEvent.mMetaState;
1838 mDeviceId = origEvent.mDeviceId;
1839 mSource = origEvent.mSource;
1840 mDisplayId = origEvent.mDisplayId;
1841 mHmac = null; // Don't copy the hmac, it will be invalid since action is changing
1842 mScanCode = origEvent.mScanCode;
1843 mFlags = origEvent.mFlags;
1844 // Don't copy mCharacters, since one way or the other we'll lose it
1845 // when changing the action.
1846 }
1847
1848 /**
1849 * Create a new key event that is the same as the given one, but whose
1850 * action is replaced with the given value.
1851 *
1852 * @param event The existing event to be copied. This is not modified.
1853 * @param action The new action code of the event.
1854 */
1855 public static KeyEvent changeAction(KeyEvent event, int action) {
1856 return new KeyEvent(event, action);
1857 }
1858
1859 /**
1860 * Create a new key event that is the same as the given one, but whose
1861 * flags are replaced with the given value.
1862 *
1863 * @param event The existing event to be copied. This is not modified.
1864 * @param flags The new flags constant.
1865 */
1866 public static KeyEvent changeFlags(KeyEvent event, int flags) {
1867 event = new KeyEvent(event);
1868 event.mId = nativeNextId(); // Not an exact copy so assign a new ID.
1869 event.mFlags = flags;
1870 return event;
1871 }
1872
1873 /** @hide */
1874 @Override
1875 public final boolean isTainted() {
1876 return (mFlags & FLAG_TAINTED) != 0;
1877 }
1878
1879 /** @hide */
1880 @Override
1881 public final void setTainted(boolean tainted) {
1882 mFlags = tainted ? mFlags | FLAG_TAINTED : mFlags & ~FLAG_TAINTED;
1883 }
1884
1885 /**
1886 * Don't use in new code, instead explicitly check
1887 * {@link #getAction()}.
1888 *
1889 * @return If the action is ACTION_DOWN, returns true; else false.
1890 *
1891 * @deprecated
1892 * @hide
1893 */
1894 @UnsupportedAppUsage
1895 @Deprecated public final boolean isDown() {
1896 return mAction == ACTION_DOWN;
1897 }
1898
1899 /** Is this a system key? System keys can not be used for menu shortcuts.
1900 */
1901 public final boolean isSystem() {
1902 return isSystemKey(mKeyCode);
1903 }
1904
1905 /** @hide */
1906 public final boolean isWakeKey() {
1907 return isWakeKey(mKeyCode);
1908 }
1909
1910 /**
1911 * Returns true if the specified keycode is a gamepad button.
1912 * @return True if the keycode is a gamepad button, such as {@link #KEYCODE_BUTTON_A}.
1913 */
1914 public static final boolean isGamepadButton(int keyCode) {
1915 switch (keyCode) {
1916 case KeyEvent.KEYCODE_BUTTON_A:
1917 case KeyEvent.KEYCODE_BUTTON_B:
1918 case KeyEvent.KEYCODE_BUTTON_C:
1919 case KeyEvent.KEYCODE_BUTTON_X:
1920 case KeyEvent.KEYCODE_BUTTON_Y:
1921 case KeyEvent.KEYCODE_BUTTON_Z:
1922 case KeyEvent.KEYCODE_BUTTON_L1:
1923 case KeyEvent.KEYCODE_BUTTON_R1:
1924 case KeyEvent.KEYCODE_BUTTON_L2:
1925 case KeyEvent.KEYCODE_BUTTON_R2:
1926 case KeyEvent.KEYCODE_BUTTON_THUMBL:
1927 case KeyEvent.KEYCODE_BUTTON_THUMBR:
1928 case KeyEvent.KEYCODE_BUTTON_START:
1929 case KeyEvent.KEYCODE_BUTTON_SELECT:
1930 case KeyEvent.KEYCODE_BUTTON_MODE:
1931 case KeyEvent.KEYCODE_BUTTON_1:
1932 case KeyEvent.KEYCODE_BUTTON_2:
1933 case KeyEvent.KEYCODE_BUTTON_3:
1934 case KeyEvent.KEYCODE_BUTTON_4:
1935 case KeyEvent.KEYCODE_BUTTON_5:
1936 case KeyEvent.KEYCODE_BUTTON_6:
1937 case KeyEvent.KEYCODE_BUTTON_7:
1938 case KeyEvent.KEYCODE_BUTTON_8:
1939 case KeyEvent.KEYCODE_BUTTON_9:
1940 case KeyEvent.KEYCODE_BUTTON_10:
1941 case KeyEvent.KEYCODE_BUTTON_11:
1942 case KeyEvent.KEYCODE_BUTTON_12:
1943 case KeyEvent.KEYCODE_BUTTON_13:
1944 case KeyEvent.KEYCODE_BUTTON_14:
1945 case KeyEvent.KEYCODE_BUTTON_15:
1946 case KeyEvent.KEYCODE_BUTTON_16:
1947 return true;
1948 default:
1949 return false;
1950 }
1951 }
1952
1953 /** Whether key will, by default, trigger a click on the focused view.
1954 * @hide
1955 */
1956 @UnsupportedAppUsage
1957 public static final boolean isConfirmKey(int keyCode) {
1958 switch (keyCode) {
1959 case KeyEvent.KEYCODE_DPAD_CENTER:
1960 case KeyEvent.KEYCODE_ENTER:
1961 case KeyEvent.KEYCODE_SPACE:
1962 case KeyEvent.KEYCODE_NUMPAD_ENTER:
1963 return true;
1964 default:
1965 return false;
1966 }
1967 }
1968
1969 /**
1970 * Returns whether this key will be sent to the
1971 * {@link android.media.session.MediaSession.Callback} if not handled.
1972 */
1973 public static final boolean isMediaSessionKey(int keyCode) {
1974 switch (keyCode) {
1975 case KeyEvent.KEYCODE_MEDIA_PLAY:
1976 case KeyEvent.KEYCODE_MEDIA_PAUSE:
1977 case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
1978 case KeyEvent.KEYCODE_HEADSETHOOK:
1979 case KeyEvent.KEYCODE_MEDIA_STOP:
1980 case KeyEvent.KEYCODE_MEDIA_NEXT:
1981 case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
1982 case KeyEvent.KEYCODE_MEDIA_REWIND:
1983 case KeyEvent.KEYCODE_MEDIA_RECORD:
1984 case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
1985 return true;
1986 }
1987 return false;
1988 }
1989
1990 /** Is this a system key? System keys can not be used for menu shortcuts.
1991 * @hide
1992 */
1993 public static final boolean isSystemKey(int keyCode) {
1994 switch (keyCode) {
1995 case KeyEvent.KEYCODE_MENU:
1996 case KeyEvent.KEYCODE_SOFT_RIGHT:
1997 case KeyEvent.KEYCODE_HOME:
1998 case KeyEvent.KEYCODE_BACK:
1999 case KeyEvent.KEYCODE_CALL:
2000 case KeyEvent.KEYCODE_ENDCALL:
2001 case KeyEvent.KEYCODE_VOLUME_UP:
2002 case KeyEvent.KEYCODE_VOLUME_DOWN:
2003 case KeyEvent.KEYCODE_VOLUME_MUTE:
2004 case KeyEvent.KEYCODE_MUTE:
2005 case KeyEvent.KEYCODE_POWER:
2006 case KeyEvent.KEYCODE_HEADSETHOOK:
2007 case KeyEvent.KEYCODE_MEDIA_PLAY:
2008 case KeyEvent.KEYCODE_MEDIA_PAUSE:
2009 case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
2010 case KeyEvent.KEYCODE_MEDIA_STOP:
2011 case KeyEvent.KEYCODE_MEDIA_NEXT:
2012 case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
2013 case KeyEvent.KEYCODE_MEDIA_REWIND:
2014 case KeyEvent.KEYCODE_MEDIA_RECORD:
2015 case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
2016 case KeyEvent.KEYCODE_CAMERA:
2017 case KeyEvent.KEYCODE_FOCUS:
2018 case KeyEvent.KEYCODE_SEARCH:
2019 case KeyEvent.KEYCODE_BRIGHTNESS_DOWN:
2020 case KeyEvent.KEYCODE_BRIGHTNESS_UP:
2021 case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
2022 case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_UP:
2023 case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN:
2024 case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_LEFT:
2025 case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_RIGHT:
2026 return true;
2027 }
2028
2029 return false;
2030 }
2031
2032 /** @hide */
2033 public static final boolean isWakeKey(int keyCode) {
2034 switch (keyCode) {
2035 case KeyEvent.KEYCODE_CAMERA:
2036 case KeyEvent.KEYCODE_MENU:
2037 case KeyEvent.KEYCODE_PAIRING:
2038 case KeyEvent.KEYCODE_STEM_1:
2039 case KeyEvent.KEYCODE_STEM_2:
2040 case KeyEvent.KEYCODE_STEM_3:
2041 case KeyEvent.KEYCODE_WAKEUP:
2042 return true;
2043 }
2044 return false;
2045 }
2046
2047 /** @hide */
2048 public static final boolean isMetaKey(int keyCode) {
2049 return keyCode == KeyEvent.KEYCODE_META_LEFT || keyCode == KeyEvent.KEYCODE_META_RIGHT;
2050 }
2051
2052 /** @hide */
2053 public static final boolean isAltKey(int keyCode) {
2054 return keyCode == KeyEvent.KEYCODE_ALT_LEFT || keyCode == KeyEvent.KEYCODE_ALT_RIGHT;
2055 }
2056
2057 /** {@inheritDoc} */
2058 @Override
2059 public final int getDeviceId() {
2060 return mDeviceId;
2061 }
2062
2063 /** {@inheritDoc} */
2064 @Override
2065 public final int getSource() {
2066 return mSource;
2067 }
2068
2069 /** {@inheritDoc} */
2070 @Override
2071 public final void setSource(int source) {
2072 mSource = source;
2073 }
2074
2075 /** @hide */
2076 @Override
2077 public final int getDisplayId() {
2078 return mDisplayId;
2079 }
2080
2081 /** @hide */
2082 @TestApi
2083 @Override
2084 public final void setDisplayId(int displayId) {
2085 mDisplayId = displayId;
2086 }
2087
2088 /**
2089 * <p>Returns the state of the meta keys.</p>
2090 *
2091 * @return an integer in which each bit set to 1 represents a pressed
2092 * meta key
2093 *
2094 * @see #isAltPressed()
2095 * @see #isShiftPressed()
2096 * @see #isSymPressed()
2097 * @see #isCtrlPressed()
2098 * @see #isMetaPressed()
2099 * @see #isFunctionPressed()
2100 * @see #isCapsLockOn()
2101 * @see #isNumLockOn()
2102 * @see #isScrollLockOn()
2103 * @see #META_ALT_ON
2104 * @see #META_ALT_LEFT_ON
2105 * @see #META_ALT_RIGHT_ON
2106 * @see #META_SHIFT_ON
2107 * @see #META_SHIFT_LEFT_ON
2108 * @see #META_SHIFT_RIGHT_ON
2109 * @see #META_SYM_ON
2110 * @see #META_FUNCTION_ON
2111 * @see #META_CTRL_ON
2112 * @see #META_CTRL_LEFT_ON
2113 * @see #META_CTRL_RIGHT_ON
2114 * @see #META_META_ON
2115 * @see #META_META_LEFT_ON
2116 * @see #META_META_RIGHT_ON
2117 * @see #META_CAPS_LOCK_ON
2118 * @see #META_NUM_LOCK_ON
2119 * @see #META_SCROLL_LOCK_ON
2120 * @see #getModifiers
2121 */
2122 public final int getMetaState() {
2123 return mMetaState;
2124 }
2125
2126 /**
2127 * Returns the state of the modifier keys.
2128 * <p>
2129 * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2130 * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2131 * not considered modifier keys. Consequently, this function specifically masks out
2132 * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2133 * </p><p>
2134 * The value returned consists of the meta state (from {@link #getMetaState})
2135 * normalized using {@link #normalizeMetaState(int)} and then masked with
2136 * {@link #getModifierMetaStateMask} so that only valid modifier bits are retained.
2137 * </p>
2138 *
2139 * @return An integer in which each bit set to 1 represents a pressed modifier key.
2140 * @see #getMetaState
2141 */
2142 public final int getModifiers() {
2143 return normalizeMetaState(mMetaState) & META_MODIFIER_MASK;
2144 }
2145
2146 /**
2147 * Modifies the flags of the event.
2148 *
2149 * @param newFlags New flags for the event, replacing the entire value.
2150 * @hide
2151 */
2152 public final void setFlags(int newFlags) {
2153 mFlags = newFlags;
2154 }
2155
2156 /**
2157 * Returns the flags for this key event.
2158 *
2159 * @see #FLAG_WOKE_HERE
2160 */
2161 public final int getFlags() {
2162 return mFlags;
2163 }
2164
2165 // Mask of all modifier key meta states. Specifically excludes locked keys like caps lock.
2166 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2167 private static final int META_MODIFIER_MASK =
2168 META_SHIFT_ON | META_SHIFT_LEFT_ON | META_SHIFT_RIGHT_ON
2169 | META_ALT_ON | META_ALT_LEFT_ON | META_ALT_RIGHT_ON
2170 | META_CTRL_ON | META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON
2171 | META_META_ON | META_META_LEFT_ON | META_META_RIGHT_ON
2172 | META_SYM_ON | META_FUNCTION_ON;
2173
2174 // Mask of all lock key meta states.
2175 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2176 private static final int META_LOCK_MASK =
2177 META_CAPS_LOCK_ON | META_NUM_LOCK_ON | META_SCROLL_LOCK_ON;
2178
2179 // Mask of all valid meta states.
2180 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2181 private static final int META_ALL_MASK = META_MODIFIER_MASK | META_LOCK_MASK;
2182
2183 // Mask of all synthetic meta states that are reserved for API compatibility with
2184 // historical uses in MetaKeyKeyListener.
2185 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2186 private static final int META_SYNTHETIC_MASK =
2187 META_CAP_LOCKED | META_ALT_LOCKED | META_SYM_LOCKED | META_SELECTING;
2188
2189 // Mask of all meta states that are not valid use in specifying a modifier key.
2190 // These bits are known to be used for purposes other than specifying modifiers.
2191 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2192 private static final int META_INVALID_MODIFIER_MASK =
2193 META_LOCK_MASK | META_SYNTHETIC_MASK;
2194
2195 /**
2196 * Gets a mask that includes all valid modifier key meta state bits.
2197 * <p>
2198 * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2199 * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2200 * not considered modifier keys. Consequently, the mask specifically excludes
2201 * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2202 * </p>
2203 *
2204 * @return The modifier meta state mask which is a combination of
2205 * {@link #META_SHIFT_ON}, {@link #META_SHIFT_LEFT_ON}, {@link #META_SHIFT_RIGHT_ON},
2206 * {@link #META_ALT_ON}, {@link #META_ALT_LEFT_ON}, {@link #META_ALT_RIGHT_ON},
2207 * {@link #META_CTRL_ON}, {@link #META_CTRL_LEFT_ON}, {@link #META_CTRL_RIGHT_ON},
2208 * {@link #META_META_ON}, {@link #META_META_LEFT_ON}, {@link #META_META_RIGHT_ON},
2209 * {@link #META_SYM_ON}, {@link #META_FUNCTION_ON}.
2210 */
2211 public static int getModifierMetaStateMask() {
2212 return META_MODIFIER_MASK;
2213 }
2214
2215 /**
2216 * Returns true if this key code is a modifier key.
2217 * <p>
2218 * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2219 * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2220 * not considered modifier keys. Consequently, this function return false
2221 * for those keys.
2222 * </p>
2223 *
2224 * @return True if the key code is one of
2225 * {@link #KEYCODE_SHIFT_LEFT} {@link #KEYCODE_SHIFT_RIGHT},
2226 * {@link #KEYCODE_ALT_LEFT}, {@link #KEYCODE_ALT_RIGHT},
2227 * {@link #KEYCODE_CTRL_LEFT}, {@link #KEYCODE_CTRL_RIGHT},
2228 * {@link #KEYCODE_META_LEFT}, or {@link #KEYCODE_META_RIGHT},
2229 * {@link #KEYCODE_SYM}, {@link #KEYCODE_NUM}, {@link #KEYCODE_FUNCTION}.
2230 */
2231 public static boolean isModifierKey(int keyCode) {
2232 switch (keyCode) {
2233 case KEYCODE_SHIFT_LEFT:
2234 case KEYCODE_SHIFT_RIGHT:
2235 case KEYCODE_ALT_LEFT:
2236 case KEYCODE_ALT_RIGHT:
2237 case KEYCODE_CTRL_LEFT:
2238 case KEYCODE_CTRL_RIGHT:
2239 case KEYCODE_META_LEFT:
2240 case KEYCODE_META_RIGHT:
2241 case KEYCODE_SYM:
2242 case KEYCODE_NUM:
2243 case KEYCODE_FUNCTION:
2244 return true;
2245 default:
2246 return false;
2247 }
2248 }
2249
2250 /**
2251 * Normalizes the specified meta state.
2252 * <p>
2253 * The meta state is normalized such that if either the left or right modifier meta state
2254 * bits are set then the result will also include the universal bit for that modifier.
2255 * </p><p>
2256 * If the specified meta state contains {@link #META_ALT_LEFT_ON} then
2257 * the result will also contain {@link #META_ALT_ON} in addition to {@link #META_ALT_LEFT_ON}
2258 * and the other bits that were specified in the input. The same is process is
2259 * performed for shift, control and meta.
2260 * </p><p>
2261 * If the specified meta state contains synthetic meta states defined by
2262 * {@link MetaKeyKeyListener}, then those states are translated here and the original
2263 * synthetic meta states are removed from the result.
2264 * {@link MetaKeyKeyListener#META_CAP_LOCKED} is translated to {@link #META_CAPS_LOCK_ON}.
2265 * {@link MetaKeyKeyListener#META_ALT_LOCKED} is translated to {@link #META_ALT_ON}.
2266 * {@link MetaKeyKeyListener#META_SYM_LOCKED} is translated to {@link #META_SYM_ON}.
2267 * </p><p>
2268 * Undefined meta state bits are removed.
2269 * </p>
2270 *
2271 * @param metaState The meta state.
2272 * @return The normalized meta state.
2273 */
2274 public static int normalizeMetaState(int metaState) {
2275 if ((metaState & (META_SHIFT_LEFT_ON | META_SHIFT_RIGHT_ON)) != 0) {
2276 metaState |= META_SHIFT_ON;
2277 }
2278 if ((metaState & (META_ALT_LEFT_ON | META_ALT_RIGHT_ON)) != 0) {
2279 metaState |= META_ALT_ON;
2280 }
2281 if ((metaState & (META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON)) != 0) {
2282 metaState |= META_CTRL_ON;
2283 }
2284 if ((metaState & (META_META_LEFT_ON | META_META_RIGHT_ON)) != 0) {
2285 metaState |= META_META_ON;
2286 }
2287 if ((metaState & MetaKeyKeyListener.META_CAP_LOCKED) != 0) {
2288 metaState |= META_CAPS_LOCK_ON;
2289 }
2290 if ((metaState & MetaKeyKeyListener.META_ALT_LOCKED) != 0) {
2291 metaState |= META_ALT_ON;
2292 }
2293 if ((metaState & MetaKeyKeyListener.META_SYM_LOCKED) != 0) {
2294 metaState |= META_SYM_ON;
2295 }
2296 return metaState & META_ALL_MASK;
2297 }
2298
2299 /**
2300 * Returns true if no modifiers keys are pressed according to the specified meta state.
2301 * <p>
2302 * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2303 * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2304 * not considered modifier keys. Consequently, this function ignores
2305 * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2306 * </p><p>
2307 * The meta state is normalized prior to comparison using {@link #normalizeMetaState(int)}.
2308 * </p>
2309 *
2310 * @param metaState The meta state to consider.
2311 * @return True if no modifier keys are pressed.
2312 * @see #hasNoModifiers()
2313 */
2314 public static boolean metaStateHasNoModifiers(int metaState) {
2315 return (normalizeMetaState(metaState) & META_MODIFIER_MASK) == 0;
2316 }
2317
2318 /**
2319 * Returns true if only the specified modifier keys are pressed according to
2320 * the specified meta state. Returns false if a different combination of modifier
2321 * keys are pressed.
2322 * <p>
2323 * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2324 * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2325 * not considered modifier keys. Consequently, this function ignores
2326 * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2327 * </p><p>
2328 * If the specified modifier mask includes directional modifiers, such as
2329 * {@link #META_SHIFT_LEFT_ON}, then this method ensures that the
2330 * modifier is pressed on that side.
2331 * If the specified modifier mask includes non-directional modifiers, such as
2332 * {@link #META_SHIFT_ON}, then this method ensures that the modifier
2333 * is pressed on either side.
2334 * If the specified modifier mask includes both directional and non-directional modifiers
2335 * for the same type of key, such as {@link #META_SHIFT_ON} and {@link #META_SHIFT_LEFT_ON},
2336 * then this method throws an illegal argument exception.
2337 * </p>
2338 *
2339 * @param metaState The meta state to consider.
2340 * @param modifiers The meta state of the modifier keys to check. May be a combination
2341 * of modifier meta states as defined by {@link #getModifierMetaStateMask()}. May be 0 to
2342 * ensure that no modifier keys are pressed.
2343 * @return True if only the specified modifier keys are pressed.
2344 * @throws IllegalArgumentException if the modifiers parameter contains invalid modifiers
2345 * @see #hasModifiers
2346 */
2347 public static boolean metaStateHasModifiers(int metaState, int modifiers) {
2348 // Note: For forward compatibility, we allow the parameter to contain meta states
2349 // that we do not recognize but we explicitly disallow meta states that
2350 // are not valid modifiers.
2351 if ((modifiers & META_INVALID_MODIFIER_MASK) != 0) {
2352 throw new IllegalArgumentException("modifiers must not contain "
2353 + "META_CAPS_LOCK_ON, META_NUM_LOCK_ON, META_SCROLL_LOCK_ON, "
2354 + "META_CAP_LOCKED, META_ALT_LOCKED, META_SYM_LOCKED, "
2355 + "or META_SELECTING");
2356 }
2357
2358 metaState = normalizeMetaState(metaState) & META_MODIFIER_MASK;
2359 metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
2360 META_SHIFT_ON, META_SHIFT_LEFT_ON, META_SHIFT_RIGHT_ON);
2361 metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
2362 META_ALT_ON, META_ALT_LEFT_ON, META_ALT_RIGHT_ON);
2363 metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
2364 META_CTRL_ON, META_CTRL_LEFT_ON, META_CTRL_RIGHT_ON);
2365 metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
2366 META_META_ON, META_META_LEFT_ON, META_META_RIGHT_ON);
2367 return metaState == modifiers;
2368 }
2369
2370 private static int metaStateFilterDirectionalModifiers(int metaState,
2371 int modifiers, int basic, int left, int right) {
2372 final boolean wantBasic = (modifiers & basic) != 0;
2373 final int directional = left | right;
2374 final boolean wantLeftOrRight = (modifiers & directional) != 0;
2375
2376 if (wantBasic) {
2377 if (wantLeftOrRight) {
2378 throw new IllegalArgumentException("modifiers must not contain "
2379 + metaStateToString(basic) + " combined with "
2380 + metaStateToString(left) + " or " + metaStateToString(right));
2381 }
2382 return metaState & ~directional;
2383 } else if (wantLeftOrRight) {
2384 return metaState & ~basic;
2385 } else {
2386 return metaState;
2387 }
2388 }
2389
2390 /**
2391 * Returns true if no modifier keys are pressed.
2392 * <p>
2393 * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2394 * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2395 * not considered modifier keys. Consequently, this function ignores
2396 * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2397 * </p><p>
2398 * The meta state is normalized prior to comparison using {@link #normalizeMetaState(int)}.
2399 * </p>
2400 *
2401 * @return True if no modifier keys are pressed.
2402 * @see #metaStateHasNoModifiers
2403 */
2404 public final boolean hasNoModifiers() {
2405 return metaStateHasNoModifiers(mMetaState);
2406 }
2407
2408 /**
2409 * Returns true if only the specified modifiers keys are pressed.
2410 * Returns false if a different combination of modifier keys are pressed.
2411 * <p>
2412 * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2413 * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2414 * not considered modifier keys. Consequently, this function ignores
2415 * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2416 * </p><p>
2417 * If the specified modifier mask includes directional modifiers, such as
2418 * {@link #META_SHIFT_LEFT_ON}, then this method ensures that the
2419 * modifier is pressed on that side.
2420 * If the specified modifier mask includes non-directional modifiers, such as
2421 * {@link #META_SHIFT_ON}, then this method ensures that the modifier
2422 * is pressed on either side.
2423 * If the specified modifier mask includes both directional and non-directional modifiers
2424 * for the same type of key, such as {@link #META_SHIFT_ON} and {@link #META_SHIFT_LEFT_ON},
2425 * then this method throws an illegal argument exception.
2426 * </p>
2427 *
2428 * @param modifiers The meta state of the modifier keys to check. May be a combination
2429 * of modifier meta states as defined by {@link #getModifierMetaStateMask()}. May be 0 to
2430 * ensure that no modifier keys are pressed.
2431 * @return True if only the specified modifier keys are pressed.
2432 * @throws IllegalArgumentException if the modifiers parameter contains invalid modifiers
2433 * @see #metaStateHasModifiers
2434 */
2435 public final boolean hasModifiers(int modifiers) {
2436 return metaStateHasModifiers(mMetaState, modifiers);
2437 }
2438
2439 /**
2440 * <p>Returns the pressed state of the ALT meta key.</p>
2441 *
2442 * @return true if the ALT key is pressed, false otherwise
2443 *
2444 * @see #KEYCODE_ALT_LEFT
2445 * @see #KEYCODE_ALT_RIGHT
2446 * @see #META_ALT_ON
2447 */
2448 public final boolean isAltPressed() {
2449 return (mMetaState & META_ALT_ON) != 0;
2450 }
2451
2452 /**
2453 * <p>Returns the pressed state of the SHIFT meta key.</p>
2454 *
2455 * @return true if the SHIFT key is pressed, false otherwise
2456 *
2457 * @see #KEYCODE_SHIFT_LEFT
2458 * @see #KEYCODE_SHIFT_RIGHT
2459 * @see #META_SHIFT_ON
2460 */
2461 public final boolean isShiftPressed() {
2462 return (mMetaState & META_SHIFT_ON) != 0;
2463 }
2464
2465 /**
2466 * <p>Returns the pressed state of the SYM meta key.</p>
2467 *
2468 * @return true if the SYM key is pressed, false otherwise
2469 *
2470 * @see #KEYCODE_SYM
2471 * @see #META_SYM_ON
2472 */
2473 public final boolean isSymPressed() {
2474 return (mMetaState & META_SYM_ON) != 0;
2475 }
2476
2477 /**
2478 * <p>Returns the pressed state of the CTRL meta key.</p>
2479 *
2480 * @return true if the CTRL key is pressed, false otherwise
2481 *
2482 * @see #KEYCODE_CTRL_LEFT
2483 * @see #KEYCODE_CTRL_RIGHT
2484 * @see #META_CTRL_ON
2485 */
2486 public final boolean isCtrlPressed() {
2487 return (mMetaState & META_CTRL_ON) != 0;
2488 }
2489
2490 /**
2491 * <p>Returns the pressed state of the META meta key.</p>
2492 *
2493 * @return true if the META key is pressed, false otherwise
2494 *
2495 * @see #KEYCODE_META_LEFT
2496 * @see #KEYCODE_META_RIGHT
2497 * @see #META_META_ON
2498 */
2499 public final boolean isMetaPressed() {
2500 return (mMetaState & META_META_ON) != 0;
2501 }
2502
2503 /**
2504 * <p>Returns the pressed state of the FUNCTION meta key.</p>
2505 *
2506 * @return true if the FUNCTION key is pressed, false otherwise
2507 *
2508 * @see #KEYCODE_FUNCTION
2509 * @see #META_FUNCTION_ON
2510 */
2511 public final boolean isFunctionPressed() {
2512 return (mMetaState & META_FUNCTION_ON) != 0;
2513 }
2514
2515 /**
2516 * <p>Returns the locked state of the CAPS LOCK meta key.</p>
2517 *
2518 * @return true if the CAPS LOCK key is on, false otherwise
2519 *
2520 * @see #KEYCODE_CAPS_LOCK
2521 * @see #META_CAPS_LOCK_ON
2522 */
2523 public final boolean isCapsLockOn() {
2524 return (mMetaState & META_CAPS_LOCK_ON) != 0;
2525 }
2526
2527 /**
2528 * <p>Returns the locked state of the NUM LOCK meta key.</p>
2529 *
2530 * @return true if the NUM LOCK key is on, false otherwise
2531 *
2532 * @see #KEYCODE_NUM_LOCK
2533 * @see #META_NUM_LOCK_ON
2534 */
2535 public final boolean isNumLockOn() {
2536 return (mMetaState & META_NUM_LOCK_ON) != 0;
2537 }
2538
2539 /**
2540 * <p>Returns the locked state of the SCROLL LOCK meta key.</p>
2541 *
2542 * @return true if the SCROLL LOCK key is on, false otherwise
2543 *
2544 * @see #KEYCODE_SCROLL_LOCK
2545 * @see #META_SCROLL_LOCK_ON
2546 */
2547 public final boolean isScrollLockOn() {
2548 return (mMetaState & META_SCROLL_LOCK_ON) != 0;
2549 }
2550
2551 /**
2552 * Retrieve the action of this key event. May be either
2553 * {@link #ACTION_DOWN}, {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
2554 *
2555 * @return The event action: ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
2556 */
2557 public final int getAction() {
2558 return mAction;
2559 }
2560
2561 /**
2562 * For {@link #ACTION_UP} events, indicates that the event has been
2563 * canceled as per {@link #FLAG_CANCELED}.
2564 */
2565 public final boolean isCanceled() {
2566 return (mFlags&FLAG_CANCELED) != 0;
2567 }
2568
2569 /**
2570 * Set {@link #FLAG_CANCELED} flag for the key event.
2571 *
2572 * @hide
2573 */
2574 @Override
2575 public final void cancel() {
2576 mFlags |= FLAG_CANCELED;
2577 }
2578
2579 /**
2580 * Call this during {@link Callback#onKeyDown} to have the system track
2581 * the key through its final up (possibly including a long press). Note
2582 * that only one key can be tracked at a time -- if another key down
2583 * event is received while a previous one is being tracked, tracking is
2584 * stopped on the previous event.
2585 */
2586 public final void startTracking() {
2587 mFlags |= FLAG_START_TRACKING;
2588 }
2589
2590 /**
2591 * For {@link #ACTION_UP} events, indicates that the event is still being
2592 * tracked from its initial down event as per
2593 * {@link #FLAG_TRACKING}.
2594 */
2595 public final boolean isTracking() {
2596 return (mFlags&FLAG_TRACKING) != 0;
2597 }
2598
2599 /**
2600 * For {@link #ACTION_DOWN} events, indicates that the event has been
2601 * canceled as per {@link #FLAG_LONG_PRESS}.
2602 */
2603 public final boolean isLongPress() {
2604 return (mFlags&FLAG_LONG_PRESS) != 0;
2605 }
2606
2607 /**
2608 * Retrieve the key code of the key event. This is the physical key that
2609 * was pressed, <em>not</em> the Unicode character.
2610 *
2611 * @return The key code of the event.
2612 */
2613 public final int getKeyCode() {
2614 return mKeyCode;
2615 }
2616
2617 /**
2618 * For the special case of a {@link #ACTION_MULTIPLE} event with key
2619 * code of {@link #KEYCODE_UNKNOWN}, this is a raw string of characters
2620 * associated with the event. In all other cases it is null.
2621 *
2622 * @return Returns a String of 1 or more characters associated with
2623 * the event.
2624 *
2625 * @deprecated no longer used by the input system.
2626 */
2627 @Deprecated
2628 public final String getCharacters() {
2629 return mCharacters;
2630 }
2631
2632 /**
2633 * Retrieve the hardware key id of this key event. These values are not
2634 * reliable and vary from device to device.
2635 *
2636 * {@more}
2637 * Mostly this is here for debugging purposes.
2638 */
2639 public final int getScanCode() {
2640 return mScanCode;
2641 }
2642
2643 /**
2644 * Retrieve the repeat count of the event. For key down events,
2645 * this is the number of times the key has repeated with the first
2646 * down starting at 0 and counting up from there. For key up events,
2647 * this is always equal to zero. For multiple key events,
2648 * this is the number of down/up pairs that have occurred.
2649 *
2650 * @return The number of times the key has repeated.
2651 */
2652 public final int getRepeatCount() {
2653 return mRepeatCount;
2654 }
2655
2656 /**
2657 * Modifies the down time and the event time of the event.
2658 *
2659 * @param downTime The new down time (in {@link android.os.SystemClock#uptimeMillis}) of the
2660 * event.
2661 * @param eventTime The new event time (in {@link android.os.SystemClock#uptimeMillis}) of the
2662 * event.
2663 * @hide
2664 */
2665 public final void setTime(long downTime, long eventTime) {
2666 mDownTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
2667 mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
2668 }
2669
2670 /**
2671 * Retrieve the time of the most recent key down event,
2672 * in the {@link android.os.SystemClock#uptimeMillis} time base. If this
2673 * is a down event, this will be the same as {@link #getEventTime()}.
2674 * Note that when chording keys, this value is the down time of the
2675 * most recently pressed key, which may <em>not</em> be the same physical
2676 * key of this event.
2677 *
2678 * @return Returns the most recent key down time, in the
2679 * {@link android.os.SystemClock#uptimeMillis} time base
2680 */
2681 public final long getDownTime() {
2682 return TimeUnit.MILLISECONDS.convert(mDownTime, TimeUnit.NANOSECONDS);
2683 }
2684
2685 /**
2686 * Retrieve the time this event occurred,
2687 * in the {@link android.os.SystemClock#uptimeMillis} time base.
2688 *
2689 * @return Returns the time this event occurred,
2690 * in the {@link android.os.SystemClock#uptimeMillis} time base.
2691 */
2692 @Override
2693 public final long getEventTime() {
2694 return TimeUnit.MILLISECONDS.convert(mEventTime, TimeUnit.NANOSECONDS);
2695 }
2696
2697 /**
2698 * Retrieve the time this event occurred,
2699 * in the {@link android.os.SystemClock#uptimeMillis} time base but with
2700 * nanosecond (instead of millisecond) precision.
2701 * <p>
2702 * The value is in nanosecond precision but it may not have nanosecond accuracy.
2703 * </p>
2704 *
2705 * @return Returns the time this event occurred,
2706 * in the {@link android.os.SystemClock#uptimeMillis} time base but with
2707 * nanosecond (instead of millisecond) precision.
2708 *
2709 * @hide
2710 */
2711 @Override
2712 public final long getEventTimeNano() {
2713 return mEventTime;
2714 }
2715
2716 /**
2717 * Renamed to {@link #getDeviceId}.
2718 *
2719 * @hide
2720 * @deprecated use {@link #getDeviceId()} instead.
2721 */
2722 @Deprecated
2723 public final int getKeyboardDevice() {
2724 return mDeviceId;
2725 }
2726
2727 /**
2728 * Gets the {@link KeyCharacterMap} associated with the keyboard device.
2729 *
2730 * @return The associated key character map.
2731 * @throws {@link KeyCharacterMap.UnavailableException} if the key character map
2732 * could not be loaded because it was malformed or the default key character map
2733 * is missing from the system.
2734 *
2735 * @see KeyCharacterMap#load
2736 */
2737 public final KeyCharacterMap getKeyCharacterMap() {
2738 return KeyCharacterMap.load(mDeviceId);
2739 }
2740
2741 /**
2742 * Gets the primary character for this key.
2743 * In other words, the label that is physically printed on it.
2744 *
2745 * @return The display label character, or 0 if none (eg. for non-printing keys).
2746 */
2747 public char getDisplayLabel() {
2748 return getKeyCharacterMap().getDisplayLabel(mKeyCode);
2749 }
2750
2751 /**
2752 * Gets the Unicode character generated by the specified key and meta
2753 * key state combination.
2754 * <p>
2755 * Returns the Unicode character that the specified key would produce
2756 * when the specified meta bits (see {@link MetaKeyKeyListener})
2757 * were active.
2758 * </p><p>
2759 * Returns 0 if the key is not one that is used to type Unicode
2760 * characters.
2761 * </p><p>
2762 * If the return value has bit {@link KeyCharacterMap#COMBINING_ACCENT} set, the
2763 * key is a "dead key" that should be combined with another to
2764 * actually produce a character -- see {@link KeyCharacterMap#getDeadChar} --
2765 * after masking with {@link KeyCharacterMap#COMBINING_ACCENT_MASK}.
2766 * </p>
2767 *
2768 * @return The associated character or combining accent, or 0 if none.
2769 */
2770 public int getUnicodeChar() {
2771 return getUnicodeChar(mMetaState);
2772 }
2773
2774 /**
2775 * Gets the Unicode character generated by the specified key and meta
2776 * key state combination.
2777 * <p>
2778 * Returns the Unicode character that the specified key would produce
2779 * when the specified meta bits (see {@link MetaKeyKeyListener})
2780 * were active.
2781 * </p><p>
2782 * Returns 0 if the key is not one that is used to type Unicode
2783 * characters.
2784 * </p><p>
2785 * If the return value has bit {@link KeyCharacterMap#COMBINING_ACCENT} set, the
2786 * key is a "dead key" that should be combined with another to
2787 * actually produce a character -- see {@link KeyCharacterMap#getDeadChar} --
2788 * after masking with {@link KeyCharacterMap#COMBINING_ACCENT_MASK}.
2789 * </p>
2790 *
2791 * @param metaState The meta key modifier state.
2792 * @return The associated character or combining accent, or 0 if none.
2793 */
2794 public int getUnicodeChar(int metaState) {
2795 return getKeyCharacterMap().get(mKeyCode, metaState);
2796 }
2797
2798 /**
2799 * Get the character conversion data for a given key code.
2800 *
2801 * @param results A {@link KeyCharacterMap.KeyData} instance that will be
2802 * filled with the results.
2803 * @return True if the key was mapped. If the key was not mapped, results is not modified.
2804 *
2805 * @deprecated instead use {@link #getDisplayLabel()},
2806 * {@link #getNumber()} or {@link #getUnicodeChar(int)}.
2807 */
2808 @Deprecated
2809 public boolean getKeyData(KeyData results) {
2810 return getKeyCharacterMap().getKeyData(mKeyCode, results);
2811 }
2812
2813 /**
2814 * Gets the first character in the character array that can be generated
2815 * by the specified key code.
2816 * <p>
2817 * This is a convenience function that returns the same value as
2818 * {@link #getMatch(char[],int) getMatch(chars, 0)}.
2819 * </p>
2820 *
2821 * @param chars The array of matching characters to consider.
2822 * @return The matching associated character, or 0 if none.
2823 */
2824 public char getMatch(char[] chars) {
2825 return getMatch(chars, 0);
2826 }
2827
2828 /**
2829 * Gets the first character in the character array that can be generated
2830 * by the specified key code. If there are multiple choices, prefers
2831 * the one that would be generated with the specified meta key modifier state.
2832 *
2833 * @param chars The array of matching characters to consider.
2834 * @param metaState The preferred meta key modifier state.
2835 * @return The matching associated character, or 0 if none.
2836 */
2837 public char getMatch(char[] chars, int metaState) {
2838 return getKeyCharacterMap().getMatch(mKeyCode, chars, metaState);
2839 }
2840
2841 /**
2842 * Gets the number or symbol associated with the key.
2843 * <p>
2844 * The character value is returned, not the numeric value.
2845 * If the key is not a number, but is a symbol, the symbol is retuned.
2846 * </p><p>
2847 * This method is intended to to support dial pads and other numeric or
2848 * symbolic entry on keyboards where certain keys serve dual function
2849 * as alphabetic and symbolic keys. This method returns the number
2850 * or symbol associated with the key independent of whether the user
2851 * has pressed the required modifier.
2852 * </p><p>
2853 * For example, on one particular keyboard the keys on the top QWERTY row generate
2854 * numbers when ALT is pressed such that ALT-Q maps to '1'. So for that keyboard
2855 * when {@link #getNumber} is called with {@link KeyEvent#KEYCODE_Q} it returns '1'
2856 * so that the user can type numbers without pressing ALT when it makes sense.
2857 * </p>
2858 *
2859 * @return The associated numeric or symbolic character, or 0 if none.
2860 */
2861 public char getNumber() {
2862 return getKeyCharacterMap().getNumber(mKeyCode);
2863 }
2864
2865 /**
2866 * Returns true if this key produces a glyph.
2867 *
2868 * @return True if the key is a printing key.
2869 */
2870 public boolean isPrintingKey() {
2871 return getKeyCharacterMap().isPrintingKey(mKeyCode);
2872 }
2873
2874 /**
2875 * @deprecated Use {@link #dispatch(Callback, DispatcherState, Object)} instead.
2876 */
2877 @Deprecated
2878 public final boolean dispatch(Callback receiver) {
2879 return dispatch(receiver, null, null);
2880 }
2881
2882 /**
2883 * Deliver this key event to a {@link Callback} interface. If this is
2884 * an ACTION_MULTIPLE event and it is not handled, then an attempt will
2885 * be made to deliver a single normal event.
2886 *
2887 * @param receiver The Callback that will be given the event.
2888 * @param state State information retained across events.
2889 * @param target The target of the dispatch, for use in tracking.
2890 *
2891 * @return The return value from the Callback method that was called.
2892 */
2893 public final boolean dispatch(Callback receiver, DispatcherState state,
2894 Object target) {
2895 switch (mAction) {
2896 case ACTION_DOWN: {
2897 mFlags &= ~FLAG_START_TRACKING;
2898 if (DEBUG) Log.v(TAG, "Key down to " + target + " in " + state
2899 + ": " + this);
2900 boolean res = receiver.onKeyDown(mKeyCode, this);
2901 if (state != null) {
2902 if (res && mRepeatCount == 0 && (mFlags&FLAG_START_TRACKING) != 0) {
2903 if (DEBUG) Log.v(TAG, " Start tracking!");
2904 state.startTracking(this, target);
2905 } else if (isLongPress() && state.isTracking(this)) {
2906 try {
2907 if (receiver.onKeyLongPress(mKeyCode, this)) {
2908 if (DEBUG) Log.v(TAG, " Clear from long press!");
2909 state.performedLongPress(this);
2910 res = true;
2911 }
2912 } catch (AbstractMethodError e) {
2913 }
2914 }
2915 }
2916 return res;
2917 }
2918 case ACTION_UP:
2919 if (DEBUG) Log.v(TAG, "Key up to " + target + " in " + state
2920 + ": " + this);
2921 if (state != null) {
2922 state.handleUpEvent(this);
2923 }
2924 return receiver.onKeyUp(mKeyCode, this);
2925 case ACTION_MULTIPLE:
2926 final int count = mRepeatCount;
2927 final int code = mKeyCode;
2928 if (receiver.onKeyMultiple(code, count, this)) {
2929 return true;
2930 }
2931 if (code != KeyEvent.KEYCODE_UNKNOWN) {
2932 mAction = ACTION_DOWN;
2933 mRepeatCount = 0;
2934 boolean handled = receiver.onKeyDown(code, this);
2935 if (handled) {
2936 mAction = ACTION_UP;
2937 receiver.onKeyUp(code, this);
2938 }
2939 mAction = ACTION_MULTIPLE;
2940 mRepeatCount = count;
2941 return handled;
2942 }
2943 return false;
2944 }
2945 return false;
2946 }
2947
2948 /**
2949 * Use with {@link KeyEvent#dispatch(Callback, DispatcherState, Object)}
2950 * for more advanced key dispatching, such as long presses.
2951 */
2952 public static class DispatcherState {
2953 int mDownKeyCode;
2954 Object mDownTarget;
2955 SparseIntArray mActiveLongPresses = new SparseIntArray();
2956
2957 /**
2958 * Reset back to initial state.
2959 */
2960 public void reset() {
2961 if (DEBUG) Log.v(TAG, "Reset: " + this);
2962 mDownKeyCode = 0;
2963 mDownTarget = null;
2964 mActiveLongPresses.clear();
2965 }
2966
2967 /**
2968 * Stop any tracking associated with this target.
2969 */
2970 public void reset(Object target) {
2971 if (mDownTarget == target) {
2972 if (DEBUG) Log.v(TAG, "Reset in " + target + ": " + this);
2973 mDownKeyCode = 0;
2974 mDownTarget = null;
2975 }
2976 }
2977
2978 /**
2979 * Start tracking the key code associated with the given event. This
2980 * can only be called on a key down. It will allow you to see any
2981 * long press associated with the key, and will result in
2982 * {@link KeyEvent#isTracking} return true on the long press and up
2983 * events.
2984 *
2985 * <p>This is only needed if you are directly dispatching events, rather
2986 * than handling them in {@link Callback#onKeyDown}.
2987 */
2988 public void startTracking(KeyEvent event, Object target) {
2989 if (event.getAction() != ACTION_DOWN) {
2990 throw new IllegalArgumentException(
2991 "Can only start tracking on a down event");
2992 }
2993 if (DEBUG) Log.v(TAG, "Start trackingt in " + target + ": " + this);
2994 mDownKeyCode = event.getKeyCode();
2995 mDownTarget = target;
2996 }
2997
2998 /**
2999 * Return true if the key event is for a key code that is currently
3000 * being tracked by the dispatcher.
3001 */
3002 public boolean isTracking(KeyEvent event) {
3003 return mDownKeyCode == event.getKeyCode();
3004 }
3005
3006 /**
3007 * Keep track of the given event's key code as having performed an
3008 * action with a long press, so no action should occur on the up.
3009 * <p>This is only needed if you are directly dispatching events, rather
3010 * than handling them in {@link Callback#onKeyLongPress}.
3011 */
3012 public void performedLongPress(KeyEvent event) {
3013 mActiveLongPresses.put(event.getKeyCode(), 1);
3014 }
3015
3016 /**
3017 * Handle key up event to stop tracking. This resets the dispatcher state,
3018 * and updates the key event state based on it.
3019 * <p>This is only needed if you are directly dispatching events, rather
3020 * than handling them in {@link Callback#onKeyUp}.
3021 */
3022 public void handleUpEvent(KeyEvent event) {
3023 final int keyCode = event.getKeyCode();
3024 if (DEBUG) Log.v(TAG, "Handle key up " + event + ": " + this);
3025 int index = mActiveLongPresses.indexOfKey(keyCode);
3026 if (index >= 0) {
3027 if (DEBUG) Log.v(TAG, " Index: " + index);
3028 event.mFlags |= FLAG_CANCELED | FLAG_CANCELED_LONG_PRESS;
3029 mActiveLongPresses.removeAt(index);
3030 }
3031 if (mDownKeyCode == keyCode) {
3032 if (DEBUG) Log.v(TAG, " Tracking!");
3033 event.mFlags |= FLAG_TRACKING;
3034 mDownKeyCode = 0;
3035 mDownTarget = null;
3036 }
3037 }
3038 }
3039
3040 @Override
3041 public String toString() {
3042 StringBuilder msg = new StringBuilder();
3043 msg.append("KeyEvent { action=").append(actionToString(mAction));
3044 msg.append(", keyCode=").append(keyCodeToString(mKeyCode));
3045 msg.append(", scanCode=").append(mScanCode);
3046 if (mCharacters != null) {
3047 msg.append(", characters=\"").append(mCharacters).append("\"");
3048 }
3049 msg.append(", metaState=").append(metaStateToString(mMetaState));
3050 msg.append(", flags=0x").append(Integer.toHexString(mFlags));
3051 msg.append(", repeatCount=").append(mRepeatCount);
3052 msg.append(", eventTime=").append(mEventTime);
3053 msg.append(", downTime=").append(mDownTime);
3054 msg.append(", deviceId=").append(mDeviceId);
3055 msg.append(", source=0x").append(Integer.toHexString(mSource));
3056 msg.append(", displayId=").append(mDisplayId);
3057 msg.append(" }");
3058 return msg.toString();
3059 }
3060
3061 /**
3062 * Returns a string that represents the symbolic name of the specified action
3063 * such as "ACTION_DOWN", or an equivalent numeric constant such as "35" if unknown.
3064 *
3065 * @param action The action.
3066 * @return The symbolic name of the specified action.
3067 * @hide
3068 */
3069 @TestApi
3070 public static String actionToString(int action) {
3071 switch (action) {
3072 case ACTION_DOWN:
3073 return "ACTION_DOWN";
3074 case ACTION_UP:
3075 return "ACTION_UP";
3076 case ACTION_MULTIPLE:
3077 return "ACTION_MULTIPLE";
3078 default:
3079 return Integer.toString(action);
3080 }
3081 }
3082
3083 /**
3084 * Returns a string that represents the symbolic name of the specified keycode
3085 * such as "KEYCODE_A", "KEYCODE_DPAD_UP", or an equivalent numeric constant
3086 * such as "1001" if unknown.
3087 *
3088 * This function is intended to be used mostly for debugging, logging, and testing. It is not
3089 * locale-specific and is not intended to be used in a user-facing manner.
3090 *
3091 * @param keyCode The key code.
3092 * @return The symbolic name of the specified keycode.
3093 *
3094 * @see KeyCharacterMap#getDisplayLabel
3095 */
3096 public static String keyCodeToString(int keyCode) {
3097 String symbolicName = nativeKeyCodeToString(keyCode);
3098 return symbolicName != null ? LABEL_PREFIX + symbolicName : Integer.toString(keyCode);
3099 }
3100
3101 /**
3102 * Gets a keycode by its symbolic name such as "KEYCODE_A" or an equivalent
3103 * numeric constant such as "29". For symbolic names,
3104 * starting in {@link android.os.Build.VERSION_CODES#Q} the prefix "KEYCODE_" is optional.
3105 *
3106 * @param symbolicName The symbolic name of the keycode.
3107 * @return The keycode or {@link #KEYCODE_UNKNOWN} if not found.
3108 * @see #keyCodeToString(int)
3109 */
3110 public static int keyCodeFromString(@NonNull String symbolicName) {
3111 try {
3112 int keyCode = Integer.parseInt(symbolicName);
3113 if (keyCodeIsValid(keyCode)) {
3114 return keyCode;
3115 }
3116 } catch (NumberFormatException ex) {
3117 }
3118
3119 if (symbolicName.startsWith(LABEL_PREFIX)) {
3120 symbolicName = symbolicName.substring(LABEL_PREFIX.length());
3121 }
3122 int keyCode = nativeKeyCodeFromString(symbolicName);
3123 if (keyCodeIsValid(keyCode)) {
3124 return keyCode;
3125 }
3126 return KEYCODE_UNKNOWN;
3127 }
3128
3129 private static boolean keyCodeIsValid(int keyCode) {
3130 return keyCode >= KEYCODE_UNKNOWN && keyCode <= LAST_KEYCODE;
3131 }
3132
3133 /**
3134 * Returns a string that represents the symbolic name of the specified combined meta
3135 * key modifier state flags such as "0", "META_SHIFT_ON",
3136 * "META_ALT_ON|META_SHIFT_ON" or an equivalent numeric constant such as "0x10000000"
3137 * if unknown.
3138 *
3139 * @param metaState The meta state.
3140 * @return The symbolic name of the specified combined meta state flags.
3141 * @hide
3142 */
3143 public static String metaStateToString(int metaState) {
3144 if (metaState == 0) {
3145 return "0";
3146 }
3147 StringBuilder result = null;
3148 int i = 0;
3149 while (metaState != 0) {
3150 final boolean isSet = (metaState & 1) != 0;
3151 metaState >>>= 1; // unsigned shift!
3152 if (isSet) {
3153 final String name = META_SYMBOLIC_NAMES[i];
3154 if (result == null) {
3155 if (metaState == 0) {
3156 return name;
3157 }
3158 result = new StringBuilder(name);
3159 } else {
3160 result.append('|');
3161 result.append(name);
3162 }
3163 }
3164 i += 1;
3165 }
3166 return result.toString();
3167 }
3168
3169 public static final @android.annotation.NonNull Parcelable.Creator<KeyEvent> CREATOR
3170 = new Parcelable.Creator<KeyEvent>() {
3171 @Override
3172 public KeyEvent createFromParcel(Parcel in) {
3173 in.readInt(); // skip token, we already know this is a KeyEvent
3174 return KeyEvent.createFromParcelBody(in);
3175 }
3176
3177 @Override
3178 public KeyEvent[] newArray(int size) {
3179 return new KeyEvent[size];
3180 }
3181 };
3182
3183 /** @hide */
3184 public static KeyEvent createFromParcelBody(Parcel in) {
3185 return new KeyEvent(in);
3186 }
3187
3188 private KeyEvent(Parcel in) {
3189 mId = in.readInt();
3190 mDeviceId = in.readInt();
3191 mSource = in.readInt();
3192 mDisplayId = in.readInt();
3193 mHmac = in.createByteArray();
3194 mAction = in.readInt();
3195 mKeyCode = in.readInt();
3196 mRepeatCount = in.readInt();
3197 mMetaState = in.readInt();
3198 mScanCode = in.readInt();
3199 mFlags = in.readInt();
3200 mDownTime = in.readLong();
3201 mEventTime = in.readLong();
3202 mCharacters = in.readString();
3203 }
3204
3205 @Override
3206 public void writeToParcel(Parcel out, int flags) {
3207 out.writeInt(PARCEL_TOKEN_KEY_EVENT);
3208
3209 out.writeInt(mId);
3210 out.writeInt(mDeviceId);
3211 out.writeInt(mSource);
3212 out.writeInt(mDisplayId);
3213 out.writeByteArray(mHmac);
3214 out.writeInt(mAction);
3215 out.writeInt(mKeyCode);
3216 out.writeInt(mRepeatCount);
3217 out.writeInt(mMetaState);
3218 out.writeInt(mScanCode);
3219 out.writeInt(mFlags);
3220 out.writeLong(mDownTime);
3221 out.writeLong(mEventTime);
3222 out.writeString(mCharacters);
3223 }
3224 }