• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     /** Key code constant: Keyboard backlight down */
870     public static final int KEYCODE_KEYBOARD_BACKLIGHT_DOWN = 305;
871     /** Key code constant: Keyboard backlight up */
872     public static final int KEYCODE_KEYBOARD_BACKLIGHT_UP = 306;
873     /** Key code constant: Keyboard backlight toggle */
874     public static final int KEYCODE_KEYBOARD_BACKLIGHT_TOGGLE = 307;
875     /**
876      * Key code constant: The primary button on the barrel of a stylus.
877      * This is usually the button closest to the tip of the stylus.
878      */
879     public static final int KEYCODE_STYLUS_BUTTON_PRIMARY = 308;
880     /**
881      * Key code constant: The secondary button on the barrel of a stylus.
882      * This is usually the second button from the tip of the stylus.
883      */
884     public static final int KEYCODE_STYLUS_BUTTON_SECONDARY = 309;
885     /**
886      * Key code constant: The tertiary button on the barrel of a stylus.
887      * This is usually the third button from the tip of the stylus.
888      */
889     public static final int KEYCODE_STYLUS_BUTTON_TERTIARY = 310;
890     /**
891      * Key code constant: A button on the tail end of a stylus.
892      * The use of this button does not usually correspond to the function of an eraser.
893      */
894     public static final int KEYCODE_STYLUS_BUTTON_TAIL = 311;
895     /**
896      * Key code constant: To open recent apps view (a.k.a. Overview).
897      * This key is handled by the framework and is never delivered to applications.
898      */
899     public static final int KEYCODE_RECENT_APPS = 312;
900     /**
901      * Key code constant: A button whose usage can be customized by the user through
902      *                    the system.
903      * User customizable key #1.
904      */
905     public static final int KEYCODE_MACRO_1 = 313;
906     /**
907      * Key code constant: A button whose usage can be customized by the user through
908      *                    the system.
909      * User customizable key #2.
910      */
911     public static final int KEYCODE_MACRO_2 = 314;
912     /**
913      * Key code constant: A button whose usage can be customized by the user through
914      *                    the system.
915      * User customizable key #3.
916      */
917     public static final int KEYCODE_MACRO_3 = 315;
918     /**
919      * Key code constant: A button whose usage can be customized by the user through
920      *                    the system.
921      * User customizable key #4.
922      */
923     public static final int KEYCODE_MACRO_4 = 316;
924 
925 
926    /**
927      * Integer value of the last KEYCODE. Increases as new keycodes are added to KeyEvent.
928      * @hide
929      */
930     @TestApi
931     public static final int LAST_KEYCODE = KEYCODE_MACRO_4;
932 
933     // NOTE: If you add a new keycode here you must also add it to:
934     //  isSystem()
935     //  isWakeKey()
936     //  frameworks/native/include/android/keycodes.h
937     //  frameworks/native/include/input/InputEventLabels.h
938     //  frameworks/base/core/res/res/values/attrs.xml
939     //  emulator?
940     //  LAST_KEYCODE
941     //
942     //  Also Android currently does not reserve code ranges for vendor-
943     //  specific key codes.  If you have new key codes to have, you
944     //  MUST contribute a patch to the open source project to define
945     //  those new codes.  This is intended to maintain a consistent
946     //  set of key code definitions across all Android devices.
947 
948     // Symbolic names of all metakeys in bit order from least significant to most significant.
949     // Accordingly there are exactly 32 values in this table.
950     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
951     private static final String[] META_SYMBOLIC_NAMES = new String[] {
952         "META_SHIFT_ON",
953         "META_ALT_ON",
954         "META_SYM_ON",
955         "META_FUNCTION_ON",
956         "META_ALT_LEFT_ON",
957         "META_ALT_RIGHT_ON",
958         "META_SHIFT_LEFT_ON",
959         "META_SHIFT_RIGHT_ON",
960         "META_CAP_LOCKED",
961         "META_ALT_LOCKED",
962         "META_SYM_LOCKED",
963         "0x00000800",
964         "META_CTRL_ON",
965         "META_CTRL_LEFT_ON",
966         "META_CTRL_RIGHT_ON",
967         "0x00008000",
968         "META_META_ON",
969         "META_META_LEFT_ON",
970         "META_META_RIGHT_ON",
971         "0x00080000",
972         "META_CAPS_LOCK_ON",
973         "META_NUM_LOCK_ON",
974         "META_SCROLL_LOCK_ON",
975         "0x00800000",
976         "0x01000000",
977         "0x02000000",
978         "0x04000000",
979         "0x08000000",
980         "0x10000000",
981         "0x20000000",
982         "0x40000000",
983         "0x80000000",
984     };
985 
986     private static final String LABEL_PREFIX = "KEYCODE_";
987 
988     /**
989      * @deprecated There are now more than MAX_KEYCODE keycodes.
990      * Use {@link #getMaxKeyCode()} instead.
991      */
992     @Deprecated
993     public static final int MAX_KEYCODE             = 84;
994 
995     /**
996      * {@link #getAction} value: the key has been pressed down.
997      */
998     public static final int ACTION_DOWN             = 0;
999     /**
1000      * {@link #getAction} value: the key has been released.
1001      */
1002     public static final int ACTION_UP               = 1;
1003     /**
1004      * @deprecated No longer used by the input system.
1005      * {@link #getAction} value: multiple duplicate key events have
1006      * occurred in a row, or a complex string is being delivered.  If the
1007      * key code is not {@link #KEYCODE_UNKNOWN} then the
1008      * {@link #getRepeatCount()} method returns the number of times
1009      * the given key code should be executed.
1010      * Otherwise, if the key code is {@link #KEYCODE_UNKNOWN}, then
1011      * this is a sequence of characters as returned by {@link #getCharacters}.
1012      */
1013     @Deprecated
1014     public static final int ACTION_MULTIPLE         = 2;
1015 
1016     /**
1017      * SHIFT key locked in CAPS mode.
1018      * Reserved for use by {@link MetaKeyKeyListener} for a published constant in its API.
1019      * @hide
1020      */
1021     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1022     public static final int META_CAP_LOCKED = 0x100;
1023 
1024     /**
1025      * ALT key locked.
1026      * Reserved for use by {@link MetaKeyKeyListener} for a published constant in its API.
1027      * @hide
1028      */
1029     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1030     public static final int META_ALT_LOCKED = 0x200;
1031 
1032     /**
1033      * SYM key locked.
1034      * Reserved for use by {@link MetaKeyKeyListener} for a published constant in its API.
1035      * @hide
1036      */
1037     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1038     public static final int META_SYM_LOCKED = 0x400;
1039 
1040     /**
1041      * Text is in selection mode.
1042      * Reserved for use by {@link MetaKeyKeyListener} for a private unpublished constant
1043      * in its API that is currently being retained for legacy reasons.
1044      * @hide
1045      */
1046     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1047     public static final int META_SELECTING = 0x800;
1048 
1049     /**
1050      * <p>This mask is used to check whether one of the ALT meta keys is pressed.</p>
1051      *
1052      * @see #isAltPressed()
1053      * @see #getMetaState()
1054      * @see #KEYCODE_ALT_LEFT
1055      * @see #KEYCODE_ALT_RIGHT
1056      */
1057     public static final int META_ALT_ON = 0x02;
1058 
1059     /**
1060      * <p>This mask is used to check whether the left ALT meta key is pressed.</p>
1061      *
1062      * @see #isAltPressed()
1063      * @see #getMetaState()
1064      * @see #KEYCODE_ALT_LEFT
1065      */
1066     public static final int META_ALT_LEFT_ON = 0x10;
1067 
1068     /**
1069      * <p>This mask is used to check whether the right the ALT meta key is pressed.</p>
1070      *
1071      * @see #isAltPressed()
1072      * @see #getMetaState()
1073      * @see #KEYCODE_ALT_RIGHT
1074      */
1075     public static final int META_ALT_RIGHT_ON = 0x20;
1076 
1077     /**
1078      * <p>This mask is used to check whether one of the SHIFT meta keys is pressed.</p>
1079      *
1080      * @see #isShiftPressed()
1081      * @see #getMetaState()
1082      * @see #KEYCODE_SHIFT_LEFT
1083      * @see #KEYCODE_SHIFT_RIGHT
1084      */
1085     public static final int META_SHIFT_ON = 0x1;
1086 
1087     /**
1088      * <p>This mask is used to check whether the left SHIFT meta key is pressed.</p>
1089      *
1090      * @see #isShiftPressed()
1091      * @see #getMetaState()
1092      * @see #KEYCODE_SHIFT_LEFT
1093      */
1094     public static final int META_SHIFT_LEFT_ON = 0x40;
1095 
1096     /**
1097      * <p>This mask is used to check whether the right SHIFT meta key is pressed.</p>
1098      *
1099      * @see #isShiftPressed()
1100      * @see #getMetaState()
1101      * @see #KEYCODE_SHIFT_RIGHT
1102      */
1103     public static final int META_SHIFT_RIGHT_ON = 0x80;
1104 
1105     /**
1106      * <p>This mask is used to check whether the SYM meta key is pressed.</p>
1107      *
1108      * @see #isSymPressed()
1109      * @see #getMetaState()
1110      */
1111     public static final int META_SYM_ON = 0x4;
1112 
1113     /**
1114      * <p>This mask is used to check whether the FUNCTION meta key is pressed.</p>
1115      *
1116      * @see #isFunctionPressed()
1117      * @see #getMetaState()
1118      */
1119     public static final int META_FUNCTION_ON = 0x8;
1120 
1121     /**
1122      * <p>This mask is used to check whether one of the CTRL meta keys is pressed.</p>
1123      *
1124      * @see #isCtrlPressed()
1125      * @see #getMetaState()
1126      * @see #KEYCODE_CTRL_LEFT
1127      * @see #KEYCODE_CTRL_RIGHT
1128      */
1129     public static final int META_CTRL_ON = 0x1000;
1130 
1131     /**
1132      * <p>This mask is used to check whether the left CTRL meta key is pressed.</p>
1133      *
1134      * @see #isCtrlPressed()
1135      * @see #getMetaState()
1136      * @see #KEYCODE_CTRL_LEFT
1137      */
1138     public static final int META_CTRL_LEFT_ON = 0x2000;
1139 
1140     /**
1141      * <p>This mask is used to check whether the right CTRL meta key is pressed.</p>
1142      *
1143      * @see #isCtrlPressed()
1144      * @see #getMetaState()
1145      * @see #KEYCODE_CTRL_RIGHT
1146      */
1147     public static final int META_CTRL_RIGHT_ON = 0x4000;
1148 
1149     /**
1150      * <p>This mask is used to check whether one of the META meta keys is pressed.</p>
1151      *
1152      * @see #isMetaPressed()
1153      * @see #getMetaState()
1154      * @see #KEYCODE_META_LEFT
1155      * @see #KEYCODE_META_RIGHT
1156      */
1157     public static final int META_META_ON = 0x10000;
1158 
1159     /**
1160      * <p>This mask is used to check whether the left META meta key is pressed.</p>
1161      *
1162      * @see #isMetaPressed()
1163      * @see #getMetaState()
1164      * @see #KEYCODE_META_LEFT
1165      */
1166     public static final int META_META_LEFT_ON = 0x20000;
1167 
1168     /**
1169      * <p>This mask is used to check whether the right META meta key is pressed.</p>
1170      *
1171      * @see #isMetaPressed()
1172      * @see #getMetaState()
1173      * @see #KEYCODE_META_RIGHT
1174      */
1175     public static final int META_META_RIGHT_ON = 0x40000;
1176 
1177     /**
1178      * <p>This mask is used to check whether the CAPS LOCK meta key is on.</p>
1179      *
1180      * @see #isCapsLockOn()
1181      * @see #getMetaState()
1182      * @see #KEYCODE_CAPS_LOCK
1183      */
1184     public static final int META_CAPS_LOCK_ON = 0x100000;
1185 
1186     /**
1187      * <p>This mask is used to check whether the NUM LOCK meta key is on.</p>
1188      *
1189      * @see #isNumLockOn()
1190      * @see #getMetaState()
1191      * @see #KEYCODE_NUM_LOCK
1192      */
1193     public static final int META_NUM_LOCK_ON = 0x200000;
1194 
1195     /**
1196      * <p>This mask is used to check whether the SCROLL LOCK meta key is on.</p>
1197      *
1198      * @see #isScrollLockOn()
1199      * @see #getMetaState()
1200      * @see #KEYCODE_SCROLL_LOCK
1201      */
1202     public static final int META_SCROLL_LOCK_ON = 0x400000;
1203 
1204     /**
1205      * This mask is a combination of {@link #META_SHIFT_ON}, {@link #META_SHIFT_LEFT_ON}
1206      * and {@link #META_SHIFT_RIGHT_ON}.
1207      */
1208     public static final int META_SHIFT_MASK = META_SHIFT_ON
1209             | META_SHIFT_LEFT_ON | META_SHIFT_RIGHT_ON;
1210 
1211     /**
1212      * This mask is a combination of {@link #META_ALT_ON}, {@link #META_ALT_LEFT_ON}
1213      * and {@link #META_ALT_RIGHT_ON}.
1214      */
1215     public static final int META_ALT_MASK = META_ALT_ON
1216             | META_ALT_LEFT_ON | META_ALT_RIGHT_ON;
1217 
1218     /**
1219      * This mask is a combination of {@link #META_CTRL_ON}, {@link #META_CTRL_LEFT_ON}
1220      * and {@link #META_CTRL_RIGHT_ON}.
1221      */
1222     public static final int META_CTRL_MASK = META_CTRL_ON
1223             | META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON;
1224 
1225     /**
1226      * This mask is a combination of {@link #META_META_ON}, {@link #META_META_LEFT_ON}
1227      * and {@link #META_META_RIGHT_ON}.
1228      */
1229     public static final int META_META_MASK = META_META_ON
1230             | META_META_LEFT_ON | META_META_RIGHT_ON;
1231 
1232     /**
1233      * This mask is set if the device woke because of this key event.
1234      *
1235      * @deprecated This flag will never be set by the system since the system
1236      * consumes all wake keys itself.
1237      */
1238     @Deprecated
1239     public static final int FLAG_WOKE_HERE = 0x1;
1240 
1241     /**
1242      * This mask is set if the key event was generated by a software keyboard.
1243      */
1244     public static final int FLAG_SOFT_KEYBOARD = 0x2;
1245 
1246     /**
1247      * This mask is set if we don't want the key event to cause us to leave
1248      * touch mode.
1249      */
1250     public static final int FLAG_KEEP_TOUCH_MODE = 0x4;
1251 
1252     /**
1253      * This mask is set if an event was known to come from a trusted part
1254      * of the system.  That is, the event is known to come from the user,
1255      * and could not have been spoofed by a third party component.
1256      */
1257     public static final int FLAG_FROM_SYSTEM = 0x8;
1258 
1259     /**
1260      * This mask is used for compatibility, to identify enter keys that are
1261      * coming from an IME whose enter key has been auto-labelled "next" or
1262      * "done".  This allows TextView to dispatch these as normal enter keys
1263      * for old applications, but still do the appropriate action when
1264      * receiving them.
1265      */
1266     public static final int FLAG_EDITOR_ACTION = 0x10;
1267 
1268     /**
1269      * When associated with up key events, this indicates that the key press
1270      * has been canceled.  Typically this is used with virtual touch screen
1271      * keys, where the user can slide from the virtual key area on to the
1272      * display: in that case, the application will receive a canceled up
1273      * event and should not perform the action normally associated with the
1274      * key.  Note that for this to work, the application can not perform an
1275      * action for a key until it receives an up or the long press timeout has
1276      * expired.
1277      */
1278     public static final int FLAG_CANCELED = 0x20;
1279 
1280     /**
1281      * This key event was generated by a virtual (on-screen) hard key area.
1282      * Typically this is an area of the touchscreen, outside of the regular
1283      * display, dedicated to "hardware" buttons.
1284      */
1285     public static final int FLAG_VIRTUAL_HARD_KEY = 0x40;
1286 
1287     /**
1288      * This flag is set for the first key repeat that occurs after the
1289      * long press timeout.
1290      */
1291     public static final int FLAG_LONG_PRESS = 0x80;
1292 
1293     /**
1294      * Set when a key event has {@link #FLAG_CANCELED} set because a long
1295      * press action was executed while it was down.
1296      */
1297     public static final int FLAG_CANCELED_LONG_PRESS = 0x100;
1298 
1299     /**
1300      * Set for {@link #ACTION_UP} when this event's key code is still being
1301      * tracked from its initial down.  That is, somebody requested that tracking
1302      * started on the key down and a long press has not caused
1303      * the tracking to be canceled.
1304      */
1305     public static final int FLAG_TRACKING = 0x200;
1306 
1307     /**
1308      * Set when a key event has been synthesized to implement default behavior
1309      * for an event that the application did not handle.
1310      * Fallback key events are generated by unhandled trackball motions
1311      * (to emulate a directional keypad) and by certain unhandled key presses
1312      * that are declared in the key map (such as special function numeric keypad
1313      * keys when numlock is off).
1314      */
1315     public static final int FLAG_FALLBACK = 0x400;
1316 
1317     /**
1318      * This flag indicates that this event was modified by or generated from an accessibility
1319      * service. Value = 0x800
1320      * @hide
1321      */
1322     @TestApi
1323     public static final int FLAG_IS_ACCESSIBILITY_EVENT = INPUT_EVENT_FLAG_IS_ACCESSIBILITY_EVENT;
1324 
1325     /**
1326      * Signifies that the key is being predispatched.
1327      * @hide
1328      */
1329     public static final int FLAG_PREDISPATCH = 0x20000000;
1330 
1331     /**
1332      * Private control to determine when an app is tracking a key sequence.
1333      * @hide
1334      */
1335     public static final int FLAG_START_TRACKING = 0x40000000;
1336 
1337     /**
1338      * Private flag that indicates when the system has detected that this key event
1339      * may be inconsistent with respect to the sequence of previously delivered key events,
1340      * such as when a key up event is sent but the key was not down.
1341      *
1342      * @hide
1343      * @see #isTainted
1344      * @see #setTainted
1345      */
1346     public static final int FLAG_TAINTED = 0x80000000;
1347 
1348     /**
1349      * Returns the maximum keycode.
1350      */
getMaxKeyCode()1351     public static int getMaxKeyCode() {
1352         return LAST_KEYCODE;
1353     }
1354 
1355     /**
1356      * Get the character that is produced by putting accent on the character
1357      * c.
1358      * For example, getDeadChar('`', 'e') returns &egrave;.
1359      */
getDeadChar(int accent, int c)1360     public static int getDeadChar(int accent, int c) {
1361         return KeyCharacterMap.getDeadChar(accent, c);
1362     }
1363 
1364     static final boolean DEBUG = false;
1365     static final String TAG = "KeyEvent";
1366 
1367     private static final int MAX_RECYCLED = 10;
1368     private static final Object gRecyclerLock = new Object();
1369     private static int gRecyclerUsed;
1370     private static KeyEvent gRecyclerTop;
1371 
1372     private KeyEvent mNext;
1373 
1374     private int mId;
1375     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1376     private int mDeviceId;
1377     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
1378     private int mSource;
1379     private int mDisplayId = INVALID_DISPLAY;
1380     // NOTE: mHmac is private and not used in this class, but it's used on native side / parcel.
1381     private @Nullable byte[] mHmac;
1382     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1383     private int mMetaState;
1384     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1385     private int mAction;
1386     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1387     private int mKeyCode;
1388     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1389     private int mScanCode;
1390     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1391     private int mRepeatCount;
1392     @UnsupportedAppUsage
1393     private int mFlags;
1394     /**
1395      * The time when the key initially was pressed, in nanoseconds. Only millisecond precision is
1396      * exposed as public api, so this must always be converted to / from milliseconds when used.
1397      */
1398     private long mDownTime;
1399     /**
1400      * The time when the current key event occurred. If mAction is ACTION_DOWN, then this is equal
1401      * to mDownTime. Only millisecond precision is exposed as public api, so this must always be
1402      * converted to / from milliseconds when used.
1403      */
1404     private long mEventTime;
1405     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1406     private @Nullable String mCharacters;
1407 
1408     public interface Callback {
1409         /**
1410          * Called when a key down event has occurred.  If you return true,
1411          * you can first call {@link KeyEvent#startTracking()
1412          * KeyEvent.startTracking()} to have the framework track the event
1413          * through its {@link #onKeyUp(int, KeyEvent)} and also call your
1414          * {@link #onKeyLongPress(int, KeyEvent)} if it occurs.
1415          *
1416          * @param keyCode The value in event.getKeyCode().
1417          * @param event Description of the key event.
1418          *
1419          * @return If you handled the event, return true.  If you want to allow
1420          *         the event to be handled by the next receiver, return false.
1421          */
onKeyDown(int keyCode, KeyEvent event)1422         boolean onKeyDown(int keyCode, KeyEvent event);
1423 
1424         /**
1425          * Called when a long press has occurred.  If you return true,
1426          * the final key up will have {@link KeyEvent#FLAG_CANCELED} and
1427          * {@link KeyEvent#FLAG_CANCELED_LONG_PRESS} set.  Note that in
1428          * order to receive this callback, someone in the event change
1429          * <em>must</em> return true from {@link #onKeyDown} <em>and</em>
1430          * call {@link KeyEvent#startTracking()} on the event.
1431          *
1432          * @param keyCode The value in event.getKeyCode().
1433          * @param event Description of the key event.
1434          *
1435          * @return If you handled the event, return true.  If you want to allow
1436          *         the event to be handled by the next receiver, return false.
1437          */
onKeyLongPress(int keyCode, KeyEvent event)1438         boolean onKeyLongPress(int keyCode, KeyEvent event);
1439 
1440         /**
1441          * Called when a key up event has occurred.
1442          *
1443          * @param keyCode The value in event.getKeyCode().
1444          * @param event Description of the key event.
1445          *
1446          * @return If you handled the event, return true.  If you want to allow
1447          *         the event to be handled by the next receiver, return false.
1448          */
onKeyUp(int keyCode, KeyEvent event)1449         boolean onKeyUp(int keyCode, KeyEvent event);
1450 
1451         /**
1452          * Called when a user's interaction with an analog control, such as
1453          * flinging a trackball, generates simulated down/up events for the same
1454          * key multiple times in quick succession.
1455          *
1456          * @param keyCode The value in event.getKeyCode().
1457          * @param count Number of pairs as returned by event.getRepeatCount().
1458          * @param event Description of the key event.
1459          *
1460          * @return If you handled the event, return true.  If you want to allow
1461          *         the event to be handled by the next receiver, return false.
1462          */
onKeyMultiple(int keyCode, int count, KeyEvent event)1463         boolean onKeyMultiple(int keyCode, int count, KeyEvent event);
1464     }
1465 
nativeKeyCodeToString(int keyCode)1466     private static native String nativeKeyCodeToString(int keyCode);
nativeKeyCodeFromString(String keyCode)1467     private static native int nativeKeyCodeFromString(String keyCode);
nativeNextId()1468     private static native int nativeNextId();
1469 
KeyEvent()1470     private KeyEvent() {
1471         this(/* downTime= */ 0, /* eventTime= */ 0, /* action= */ 0, /* code= */0, /* repeat= */ 0,
1472                 /* metaState= */ 0, /* deviceId= */ 0, /* scancode= */ 0, /* flags= */ 0,
1473                 /* source= */ 0, /* characters= */ null);
1474     }
1475 
1476     /**
1477      * Create a new key event.
1478      *
1479      * @param action Action code: either {@link #ACTION_DOWN},
1480      * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1481      * @param code The key code.
1482      */
KeyEvent(int action, int code)1483     public KeyEvent(int action, int code) {
1484         this(/* downTime= */ 0, /* eventTime= */ 0, action, code, /* repeat= */ 0,
1485                 /* metaState= */ 0, /* deviceId= */ KeyCharacterMap.VIRTUAL_KEYBOARD,
1486                 /* scancode= */ 0, /* flags= */ 0, /* source= */ 0, /* characters= */ null);
1487     }
1488 
1489     /**
1490      * Create a new key event.
1491      *
1492      * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1493      * at which this key code originally went down.
1494      * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1495      * at which this event happened.
1496      * @param action Action code: either {@link #ACTION_DOWN},
1497      * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1498      * @param code The key code.
1499      * @param repeat A repeat count for down events (> 0 if this is after the
1500      * initial down) or event count for multiple events.
1501      */
KeyEvent(long downTime, long eventTime, int action, int code, int repeat)1502     public KeyEvent(long downTime, long eventTime, int action,
1503                     int code, int repeat) {
1504         this(downTime, eventTime, action, code, repeat, /* metaState= */ 0,
1505                 KeyCharacterMap.VIRTUAL_KEYBOARD, /* scancode= */ 0, /* flags= */ 0,
1506                 /* source= */ 0, /* characters= */ null);
1507     }
1508 
1509     /**
1510      * Create a new key event.
1511      *
1512      * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1513      * at which this key code originally went down.
1514      * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1515      * at which this event happened.
1516      * @param action Action code: either {@link #ACTION_DOWN},
1517      * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1518      * @param code The key code.
1519      * @param repeat A repeat count for down events (> 0 if this is after the
1520      * initial down) or event count for multiple events.
1521      * @param metaState Flags indicating which meta keys are currently pressed.
1522      */
KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState)1523     public KeyEvent(long downTime, long eventTime, int action,
1524                     int code, int repeat, int metaState) {
1525         this(downTime, eventTime, action, code, repeat, metaState, KeyCharacterMap.VIRTUAL_KEYBOARD,
1526                 /* scancode= */ 0, /* flags= */ 0, /* source= */ 0, /* characters= */ null);
1527     }
1528 
1529     /**
1530      * Create a new key event.
1531      *
1532      * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1533      * at which this key code originally went down.
1534      * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1535      * at which this event happened.
1536      * @param action Action code: either {@link #ACTION_DOWN},
1537      * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1538      * @param code The key code.
1539      * @param repeat A repeat count for down events (> 0 if this is after the
1540      * initial down) or event count for multiple events.
1541      * @param metaState Flags indicating which meta keys are currently pressed.
1542      * @param deviceId The device ID that generated the key event.
1543      * @param scancode Raw device scan code of the event.
1544      */
KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode)1545     public KeyEvent(long downTime, long eventTime, int action,
1546                     int code, int repeat, int metaState,
1547                     int deviceId, int scancode) {
1548         this(downTime, eventTime, action, code, repeat, metaState, deviceId, scancode,
1549                 /* flags= */ 0, /* source= */ 0, /* characters= */ null);
1550     }
1551 
1552     /**
1553      * Create a new key event.
1554      *
1555      * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1556      * at which this key code originally went down.
1557      * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1558      * at which this event happened.
1559      * @param action Action code: either {@link #ACTION_DOWN},
1560      * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1561      * @param code The key code.
1562      * @param repeat A repeat count for down events (> 0 if this is after the
1563      * initial down) or event count for multiple events.
1564      * @param metaState Flags indicating which meta keys are currently pressed.
1565      * @param deviceId The device ID that generated the key event.
1566      * @param scancode Raw device scan code of the event.
1567      * @param flags The flags for this key event
1568      */
KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode, int flags)1569     public KeyEvent(long downTime, long eventTime, int action,
1570                     int code, int repeat, int metaState,
1571                     int deviceId, int scancode, int flags) {
1572         this(downTime, eventTime, action, code, repeat, metaState, deviceId, scancode, flags,
1573                 /* source= */ 0, /* characters= */ null);
1574     }
1575 
1576     /**
1577      * Create a new key event.
1578      *
1579      * @param downTime The time (in {@link android.os.SystemClock#uptimeMillis})
1580      * at which this key code originally went down.
1581      * @param eventTime The time (in {@link android.os.SystemClock#uptimeMillis})
1582      * at which this event happened.
1583      * @param action Action code: either {@link #ACTION_DOWN},
1584      * {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
1585      * @param code The key code.
1586      * @param repeat A repeat count for down events (> 0 if this is after the
1587      * initial down) or event count for multiple events.
1588      * @param metaState Flags indicating which meta keys are currently pressed.
1589      * @param deviceId The device ID that generated the key event.
1590      * @param scancode Raw device scan code of the event.
1591      * @param flags The flags for this key event
1592      * @param source The input source such as {@link InputDevice#SOURCE_KEYBOARD}.
1593      */
KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode, int flags, int source)1594     public KeyEvent(long downTime, long eventTime, int action,
1595                     int code, int repeat, int metaState,
1596                     int deviceId, int scancode, int flags, int source) {
1597         this(downTime, eventTime, action, code, repeat, metaState, deviceId, scancode, flags,
1598                 source, /* characters= */ null);
1599     }
1600 
KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode, int flags, int source, @Nullable String characters)1601     private KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState,
1602             int deviceId, int scancode, int flags, int source,  @Nullable String characters) {
1603         // NOTE: this is the canonical constructor, other constructors that takes KeyEvent
1604         // attributes should call it
1605         mId = nativeNextId();
1606         mDownTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
1607         mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1608         mAction = action;
1609         mKeyCode = code;
1610         mRepeatCount = repeat;
1611         mMetaState = metaState;
1612         mDeviceId = deviceId;
1613         mScanCode = scancode;
1614         mFlags = flags;
1615         mSource = source;
1616         mCharacters = characters;
1617     }
1618 
1619     /**
1620      * Create a new key event for a string of characters.  The key code,
1621      * action, repeat count and source will automatically be set to
1622      * {@link #KEYCODE_UNKNOWN}, {@link #ACTION_MULTIPLE}, 0, and
1623      * {@link InputDevice#SOURCE_KEYBOARD} for you.
1624      *
1625      * @param time The time (in {@link android.os.SystemClock#uptimeMillis})
1626      * at which this event occured.
1627      * @param characters The string of characters.
1628      * @param deviceId The device ID that generated the key event.
1629      * @param flags The flags for this key event
1630      */
KeyEvent(long time, String characters, int deviceId, int flags)1631     public KeyEvent(long time, String characters, int deviceId, int flags) {
1632         this(/* downTime= */ time, /* eventTime= */ time, ACTION_MULTIPLE, KEYCODE_UNKNOWN,
1633                 /* repeat= */ 0, /* metaState= */ 0, deviceId, /* scancode= */ 0, flags,
1634                 /* source= */ InputDevice.SOURCE_KEYBOARD, characters);
1635     }
1636 
1637     /**
1638      * Make an exact copy of an existing key event.
1639      */
KeyEvent(KeyEvent origEvent)1640     public KeyEvent(KeyEvent origEvent) {
1641         this(origEvent, origEvent.mId, origEvent.mEventTime, origEvent.mAction,
1642                 origEvent.mRepeatCount, origEvent.mHmac == null ? null : origEvent.mHmac.clone(),
1643                 origEvent.mCharacters);
1644     }
1645 
1646     /**
1647      * Copy an existing key event, modifying its time and repeat count.
1648      *
1649      * @deprecated Use {@link #changeTimeRepeat(KeyEvent, long, int)}
1650      * instead.
1651      *
1652      * @param origEvent The existing event to be copied.
1653      * @param eventTime The new event time
1654      * (in {@link android.os.SystemClock#uptimeMillis}) of the event.
1655      * @param newRepeat The new repeat count of the event.
1656      */
1657     @Deprecated
KeyEvent(KeyEvent origEvent, long eventTime, int newRepeat)1658     public KeyEvent(KeyEvent origEvent, long eventTime, int newRepeat) {
1659         // Not an exact copy so assign a new ID.
1660         // Don't copy HMAC, it will be invalid because eventTime is changing
1661         this(origEvent, nativeNextId(),
1662                 TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS), origEvent.mAction,
1663                 newRepeat, /* hmac= */ null, origEvent.mCharacters);
1664     }
1665 
1666     // This is the canonical constructor that should be called for constructors that take a KeyEvent
KeyEvent(KeyEvent origEvent, int id, long eventTime, int action, int newRepeat, @Nullable byte[] hmac, @Nullable String characters)1667     private KeyEvent(KeyEvent origEvent, int id, long eventTime, int action, int newRepeat,
1668             @Nullable byte[] hmac, @Nullable String characters) {
1669         mId = id;
1670         mDownTime = origEvent.mDownTime;
1671         mEventTime = eventTime;
1672         mAction = action;
1673         mKeyCode = origEvent.mKeyCode;
1674         mRepeatCount = newRepeat;
1675         mMetaState = origEvent.mMetaState;
1676         mDeviceId = origEvent.mDeviceId;
1677         mSource = origEvent.mSource;
1678         mDisplayId = origEvent.mDisplayId;
1679         mHmac = hmac;
1680         mScanCode = origEvent.mScanCode;
1681         mFlags = origEvent.mFlags;
1682         mCharacters = characters;
1683     }
1684 
obtain()1685     private static KeyEvent obtain() {
1686         final KeyEvent ev;
1687         synchronized (gRecyclerLock) {
1688             ev = gRecyclerTop;
1689             if (ev == null) {
1690                 return new KeyEvent();
1691             }
1692             gRecyclerTop = ev.mNext;
1693             gRecyclerUsed -= 1;
1694         }
1695         ev.mNext = null;
1696         ev.prepareForReuse();
1697         return ev;
1698     }
1699 
1700     /**
1701      * Obtains a (potentially recycled) key event. Used by native code to create a Java object.
1702      *
1703      * @hide
1704      */
obtain(int id, long downTimeNanos, long eventTimeNanos, int action, int code, int repeat, int metaState, int deviceId, int scancode, int flags, int source, int displayId, @Nullable byte[] hmac, String characters)1705     private static KeyEvent obtain(int id, long downTimeNanos, long eventTimeNanos, int action,
1706             int code, int repeat, int metaState,
1707             int deviceId, int scancode, int flags, int source, int displayId, @Nullable byte[] hmac,
1708             String characters) {
1709         KeyEvent ev = obtain();
1710         ev.mId = id;
1711         ev.mDownTime = downTimeNanos;
1712         ev.mEventTime = eventTimeNanos;
1713         ev.mAction = action;
1714         ev.mKeyCode = code;
1715         ev.mRepeatCount = repeat;
1716         ev.mMetaState = metaState;
1717         ev.mDeviceId = deviceId;
1718         ev.mScanCode = scancode;
1719         ev.mFlags = flags;
1720         ev.mSource = source;
1721         ev.mDisplayId = displayId;
1722         ev.mHmac = hmac;
1723         ev.mCharacters = characters;
1724         return ev;
1725     }
1726 
1727     /**
1728      * Obtains a (potentially recycled) key event.
1729      *
1730      * @hide
1731      */
obtain(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scanCode, int flags, int source, int displayId, String characters)1732     public static KeyEvent obtain(long downTime, long eventTime, int action,
1733             int code, int repeat, int metaState,
1734             int deviceId, int scanCode, int flags, int source, int displayId, String characters) {
1735         downTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
1736         eventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1737         return obtain(nativeNextId(), downTime, eventTime, action, code, repeat, metaState,
1738                 deviceId, scanCode, flags, source, displayId, null /* hmac */, characters);
1739     }
1740 
1741     /**
1742      * Obtains a (potentially recycled) key event.
1743      *
1744      * @hide
1745      */
1746     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
obtain(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode, int flags, int source, String characters)1747     public static KeyEvent obtain(long downTime, long eventTime, int action,
1748             int code, int repeat, int metaState,
1749             int deviceId, int scancode, int flags, int source, String characters) {
1750         // Do not convert downTime and eventTime here. We are calling the obtain method above,
1751         // which will do the conversion. Just specify INVALID_DISPLAY and forward the request.
1752         return obtain(downTime, eventTime, action, code, repeat, metaState, deviceId, scancode,
1753                 flags, source, INVALID_DISPLAY, characters);
1754     }
1755 
1756     /**
1757 
1758     /**
1759      * Obtains a (potentially recycled) copy of another key event.
1760      *
1761      * @hide
1762      */
obtain(KeyEvent other)1763     public static KeyEvent obtain(KeyEvent other) {
1764         KeyEvent ev = obtain();
1765         ev.mId = other.mId;
1766         ev.mDownTime = other.mDownTime;
1767         ev.mEventTime = other.mEventTime;
1768         ev.mAction = other.mAction;
1769         ev.mKeyCode = other.mKeyCode;
1770         ev.mRepeatCount = other.mRepeatCount;
1771         ev.mMetaState = other.mMetaState;
1772         ev.mDeviceId = other.mDeviceId;
1773         ev.mScanCode = other.mScanCode;
1774         ev.mFlags = other.mFlags;
1775         ev.mSource = other.mSource;
1776         ev.mDisplayId = other.mDisplayId;
1777         ev.mHmac = other.mHmac == null ? null : other.mHmac.clone();
1778         ev.mCharacters = other.mCharacters;
1779         return ev;
1780     }
1781 
1782     /** @hide */
1783     @Override
copy()1784     public KeyEvent copy() {
1785         return obtain(this);
1786     }
1787 
1788     /**
1789      * Recycles a key event.
1790      * Key events should only be recycled if they are owned by the system since user
1791      * code expects them to be essentially immutable, "tracking" notwithstanding.
1792      *
1793      * @hide
1794      */
1795     @Override
1796     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
recycle()1797     public final void recycle() {
1798         super.recycle();
1799         mCharacters = null;
1800 
1801         synchronized (gRecyclerLock) {
1802             if (gRecyclerUsed < MAX_RECYCLED) {
1803                 gRecyclerUsed++;
1804                 mNext = gRecyclerTop;
1805                 gRecyclerTop = this;
1806             }
1807         }
1808     }
1809 
1810     /** @hide */
1811     @Override
recycleIfNeededAfterDispatch()1812     public final void recycleIfNeededAfterDispatch() {
1813         // Do nothing.
1814     }
1815 
1816     /** @hide */
1817     @Override
getId()1818     public int getId() {
1819         return mId;
1820     }
1821 
1822     /**
1823      * Create a new key event that is the same as the given one, but whose
1824      * event time and repeat count are replaced with the given value.
1825      *
1826      * @param event The existing event to be copied.  This is not modified.
1827      * @param eventTime The new event time
1828      * (in {@link android.os.SystemClock#uptimeMillis}) of the event.
1829      * @param newRepeat The new repeat count of the event.
1830      */
changeTimeRepeat(KeyEvent event, long eventTime, int newRepeat)1831     public static KeyEvent changeTimeRepeat(KeyEvent event, long eventTime,
1832             int newRepeat) {
1833         return new KeyEvent(event, eventTime, newRepeat);
1834     }
1835 
1836     /**
1837      * Create a new key event that is the same as the given one, but whose
1838      * event time and repeat count are replaced with the given value.
1839      *
1840      * @param event The existing event to be copied.  This is not modified.
1841      * @param eventTime The new event time
1842      * (in {@link android.os.SystemClock#uptimeMillis}) of the event.
1843      * @param newRepeat The new repeat count of the event.
1844      * @param newFlags New flags for the event, replacing the entire value
1845      * in the original event.
1846      */
changeTimeRepeat(KeyEvent event, long eventTime, int newRepeat, int newFlags)1847     public static KeyEvent changeTimeRepeat(KeyEvent event, long eventTime,
1848             int newRepeat, int newFlags) {
1849         KeyEvent ret = new KeyEvent(event);
1850         ret.mId = nativeNextId();  // Not an exact copy so assign a new ID.
1851         ret.mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
1852         ret.mRepeatCount = newRepeat;
1853         ret.mFlags = newFlags;
1854         return ret;
1855     }
1856 
1857     /**
1858      * Copy an existing key event, modifying its action.
1859      *
1860      * @param origEvent The existing event to be copied.
1861      * @param action The new action code of the event.
1862      */
KeyEvent(KeyEvent origEvent, int action)1863     private KeyEvent(KeyEvent origEvent, int action) {
1864         // Not an exact copy so assign a new ID
1865         // Don't copy the hmac, it will be invalid since action is changing
1866         // Don't copy mCharacters, since one way or the other we'll lose it when changing action.
1867         this(origEvent, nativeNextId(), origEvent.mEventTime, action, origEvent.mRepeatCount,
1868                 /* hmac= */ null, /* characters= */ null);
1869     }
1870 
1871     /**
1872      * Create a new key event that is the same as the given one, but whose
1873      * action is replaced with the given value.
1874      *
1875      * @param event The existing event to be copied.  This is not modified.
1876      * @param action The new action code of the event.
1877      */
changeAction(KeyEvent event, int action)1878     public static KeyEvent changeAction(KeyEvent event, int action) {
1879         return new KeyEvent(event, action);
1880     }
1881 
1882     /**
1883      * Create a new key event that is the same as the given one, but whose
1884      * flags are replaced with the given value.
1885      *
1886      * @param event The existing event to be copied.  This is not modified.
1887      * @param flags The new flags constant.
1888      */
changeFlags(KeyEvent event, int flags)1889     public static KeyEvent changeFlags(KeyEvent event, int flags) {
1890         event = new KeyEvent(event);
1891         event.mId = nativeNextId();  // Not an exact copy so assign a new ID.
1892         event.mFlags = flags;
1893         return event;
1894     }
1895 
1896     /** @hide */
1897     @Override
isTainted()1898     public final boolean isTainted() {
1899         return (mFlags & FLAG_TAINTED) != 0;
1900     }
1901 
1902     /** @hide */
1903     @Override
setTainted(boolean tainted)1904     public final void setTainted(boolean tainted) {
1905         mFlags = tainted ? mFlags | FLAG_TAINTED : mFlags & ~FLAG_TAINTED;
1906     }
1907 
1908     /**
1909      * Don't use in new code, instead explicitly check
1910      * {@link #getAction()}.
1911      *
1912      * @return If the action is ACTION_DOWN, returns true; else false.
1913      *
1914      * @deprecated
1915      * @hide
1916      */
1917     @UnsupportedAppUsage
isDown()1918     @Deprecated public final boolean isDown() {
1919         return mAction == ACTION_DOWN;
1920     }
1921 
1922     /** Is this a system key?  System keys can not be used for menu shortcuts.
1923      */
isSystem()1924     public final boolean isSystem() {
1925         return isSystemKey(mKeyCode);
1926     }
1927 
1928     /** @hide */
isWakeKey()1929     public final boolean isWakeKey() {
1930         return isWakeKey(mKeyCode);
1931     }
1932 
1933     /**
1934      * Returns true if the specified keycode is a gamepad button.
1935      * @return True if the keycode is a gamepad button, such as {@link #KEYCODE_BUTTON_A}.
1936      */
isGamepadButton(int keyCode)1937     public static final boolean isGamepadButton(int keyCode) {
1938         switch (keyCode) {
1939             case KeyEvent.KEYCODE_BUTTON_A:
1940             case KeyEvent.KEYCODE_BUTTON_B:
1941             case KeyEvent.KEYCODE_BUTTON_C:
1942             case KeyEvent.KEYCODE_BUTTON_X:
1943             case KeyEvent.KEYCODE_BUTTON_Y:
1944             case KeyEvent.KEYCODE_BUTTON_Z:
1945             case KeyEvent.KEYCODE_BUTTON_L1:
1946             case KeyEvent.KEYCODE_BUTTON_R1:
1947             case KeyEvent.KEYCODE_BUTTON_L2:
1948             case KeyEvent.KEYCODE_BUTTON_R2:
1949             case KeyEvent.KEYCODE_BUTTON_THUMBL:
1950             case KeyEvent.KEYCODE_BUTTON_THUMBR:
1951             case KeyEvent.KEYCODE_BUTTON_START:
1952             case KeyEvent.KEYCODE_BUTTON_SELECT:
1953             case KeyEvent.KEYCODE_BUTTON_MODE:
1954             case KeyEvent.KEYCODE_BUTTON_1:
1955             case KeyEvent.KEYCODE_BUTTON_2:
1956             case KeyEvent.KEYCODE_BUTTON_3:
1957             case KeyEvent.KEYCODE_BUTTON_4:
1958             case KeyEvent.KEYCODE_BUTTON_5:
1959             case KeyEvent.KEYCODE_BUTTON_6:
1960             case KeyEvent.KEYCODE_BUTTON_7:
1961             case KeyEvent.KEYCODE_BUTTON_8:
1962             case KeyEvent.KEYCODE_BUTTON_9:
1963             case KeyEvent.KEYCODE_BUTTON_10:
1964             case KeyEvent.KEYCODE_BUTTON_11:
1965             case KeyEvent.KEYCODE_BUTTON_12:
1966             case KeyEvent.KEYCODE_BUTTON_13:
1967             case KeyEvent.KEYCODE_BUTTON_14:
1968             case KeyEvent.KEYCODE_BUTTON_15:
1969             case KeyEvent.KEYCODE_BUTTON_16:
1970                 return true;
1971             default:
1972                 return false;
1973         }
1974     }
1975 
1976     /** Whether key will, by default, trigger a click on the focused view.
1977      * @hide
1978      */
1979     @UnsupportedAppUsage
isConfirmKey(int keyCode)1980     public static final boolean isConfirmKey(int keyCode) {
1981         switch (keyCode) {
1982             case KeyEvent.KEYCODE_DPAD_CENTER:
1983             case KeyEvent.KEYCODE_ENTER:
1984             case KeyEvent.KEYCODE_SPACE:
1985             case KeyEvent.KEYCODE_NUMPAD_ENTER:
1986                 return true;
1987             default:
1988                 return false;
1989         }
1990     }
1991 
1992     /**
1993      * Returns whether this key will be sent to the
1994      * {@link android.media.session.MediaSession.Callback} if not handled.
1995      */
isMediaSessionKey(int keyCode)1996     public static final boolean isMediaSessionKey(int keyCode) {
1997         switch (keyCode) {
1998             case KeyEvent.KEYCODE_MEDIA_PLAY:
1999             case KeyEvent.KEYCODE_MEDIA_PAUSE:
2000             case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
2001             case KeyEvent.KEYCODE_HEADSETHOOK:
2002             case KeyEvent.KEYCODE_MEDIA_STOP:
2003             case KeyEvent.KEYCODE_MEDIA_NEXT:
2004             case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
2005             case KeyEvent.KEYCODE_MEDIA_REWIND:
2006             case KeyEvent.KEYCODE_MEDIA_RECORD:
2007             case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
2008                 return true;
2009         }
2010         return false;
2011     }
2012 
2013     /** Is this a system key? System keys can not be used for menu shortcuts.
2014      * @hide
2015      */
isSystemKey(int keyCode)2016     public static final boolean isSystemKey(int keyCode) {
2017         switch (keyCode) {
2018             case KeyEvent.KEYCODE_MENU:
2019             case KeyEvent.KEYCODE_SOFT_RIGHT:
2020             case KeyEvent.KEYCODE_HOME:
2021             case KeyEvent.KEYCODE_RECENT_APPS:
2022             case KeyEvent.KEYCODE_BACK:
2023             case KeyEvent.KEYCODE_CALL:
2024             case KeyEvent.KEYCODE_ENDCALL:
2025             case KeyEvent.KEYCODE_VOLUME_UP:
2026             case KeyEvent.KEYCODE_VOLUME_DOWN:
2027             case KeyEvent.KEYCODE_VOLUME_MUTE:
2028             case KeyEvent.KEYCODE_MUTE:
2029             case KeyEvent.KEYCODE_POWER:
2030             case KeyEvent.KEYCODE_HEADSETHOOK:
2031             case KeyEvent.KEYCODE_MEDIA_PLAY:
2032             case KeyEvent.KEYCODE_MEDIA_PAUSE:
2033             case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
2034             case KeyEvent.KEYCODE_MEDIA_STOP:
2035             case KeyEvent.KEYCODE_MEDIA_NEXT:
2036             case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
2037             case KeyEvent.KEYCODE_MEDIA_REWIND:
2038             case KeyEvent.KEYCODE_MEDIA_RECORD:
2039             case KeyEvent.KEYCODE_MEDIA_FAST_FORWARD:
2040             case KeyEvent.KEYCODE_CAMERA:
2041             case KeyEvent.KEYCODE_FOCUS:
2042             case KeyEvent.KEYCODE_SEARCH:
2043             case KeyEvent.KEYCODE_BRIGHTNESS_DOWN:
2044             case KeyEvent.KEYCODE_BRIGHTNESS_UP:
2045             case KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_DOWN:
2046             case KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_UP:
2047             case KeyEvent.KEYCODE_KEYBOARD_BACKLIGHT_TOGGLE:
2048             case KeyEvent.KEYCODE_MEDIA_AUDIO_TRACK:
2049             case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_UP:
2050             case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_DOWN:
2051             case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_LEFT:
2052             case KeyEvent.KEYCODE_SYSTEM_NAVIGATION_RIGHT:
2053                 return true;
2054         }
2055 
2056         return false;
2057     }
2058 
2059     /** @hide */
isWakeKey(int keyCode)2060     public static final boolean isWakeKey(int keyCode) {
2061         switch (keyCode) {
2062             case KeyEvent.KEYCODE_CAMERA:
2063             case KeyEvent.KEYCODE_MENU:
2064             case KeyEvent.KEYCODE_PAIRING:
2065             case KeyEvent.KEYCODE_STEM_1:
2066             case KeyEvent.KEYCODE_STEM_2:
2067             case KeyEvent.KEYCODE_STEM_3:
2068             case KeyEvent.KEYCODE_WAKEUP:
2069                 return true;
2070         }
2071         return false;
2072     }
2073 
2074     /** @hide */
isMetaKey(int keyCode)2075     public static final boolean isMetaKey(int keyCode) {
2076         return keyCode == KeyEvent.KEYCODE_META_LEFT || keyCode == KeyEvent.KEYCODE_META_RIGHT;
2077     }
2078 
2079     /** @hide */
isAltKey(int keyCode)2080     public static final boolean isAltKey(int keyCode) {
2081         return keyCode == KeyEvent.KEYCODE_ALT_LEFT || keyCode == KeyEvent.KEYCODE_ALT_RIGHT;
2082     }
2083 
2084     /** {@inheritDoc} */
2085     @Override
getDeviceId()2086     public final int getDeviceId() {
2087         return mDeviceId;
2088     }
2089 
2090     /** {@inheritDoc} */
2091     @Override
getSource()2092     public final int getSource() {
2093         return mSource;
2094     }
2095 
2096     /** {@inheritDoc} */
2097     @Override
setSource(int source)2098     public final void setSource(int source) {
2099         mSource = source;
2100     }
2101 
2102     /** @hide */
2103     @TestApi
2104     @Override
getDisplayId()2105     public final int getDisplayId() {
2106         return mDisplayId;
2107     }
2108 
2109     /** @hide */
2110     @TestApi
2111     @Override
setDisplayId(int displayId)2112     public final void setDisplayId(int displayId) {
2113         mDisplayId = displayId;
2114     }
2115 
2116     /**
2117      * <p>Returns the state of the meta keys.</p>
2118      *
2119      * @return an integer in which each bit set to 1 represents a pressed
2120      *         meta key
2121      *
2122      * @see #isAltPressed()
2123      * @see #isShiftPressed()
2124      * @see #isSymPressed()
2125      * @see #isCtrlPressed()
2126      * @see #isMetaPressed()
2127      * @see #isFunctionPressed()
2128      * @see #isCapsLockOn()
2129      * @see #isNumLockOn()
2130      * @see #isScrollLockOn()
2131      * @see #META_ALT_ON
2132      * @see #META_ALT_LEFT_ON
2133      * @see #META_ALT_RIGHT_ON
2134      * @see #META_SHIFT_ON
2135      * @see #META_SHIFT_LEFT_ON
2136      * @see #META_SHIFT_RIGHT_ON
2137      * @see #META_SYM_ON
2138      * @see #META_FUNCTION_ON
2139      * @see #META_CTRL_ON
2140      * @see #META_CTRL_LEFT_ON
2141      * @see #META_CTRL_RIGHT_ON
2142      * @see #META_META_ON
2143      * @see #META_META_LEFT_ON
2144      * @see #META_META_RIGHT_ON
2145      * @see #META_CAPS_LOCK_ON
2146      * @see #META_NUM_LOCK_ON
2147      * @see #META_SCROLL_LOCK_ON
2148      * @see #getModifiers
2149      */
getMetaState()2150     public final int getMetaState() {
2151         return mMetaState;
2152     }
2153 
2154     /**
2155      * Returns the state of the modifier keys.
2156      * <p>
2157      * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2158      * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2159      * not considered modifier keys.  Consequently, this function specifically masks out
2160      * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2161      * </p><p>
2162      * The value returned consists of the meta state (from {@link #getMetaState})
2163      * normalized using {@link #normalizeMetaState(int)} and then masked with
2164      * {@link #getModifierMetaStateMask} so that only valid modifier bits are retained.
2165      * </p>
2166      *
2167      * @return An integer in which each bit set to 1 represents a pressed modifier key.
2168      * @see #getMetaState
2169      */
getModifiers()2170     public final int getModifiers() {
2171         return normalizeMetaState(mMetaState) & META_MODIFIER_MASK;
2172     }
2173 
2174     /**
2175      * Modifies the flags of the event.
2176      *
2177      * @param newFlags New flags for the event, replacing the entire value.
2178      * @hide
2179      */
setFlags(int newFlags)2180     public final void setFlags(int newFlags) {
2181         mFlags = newFlags;
2182     }
2183 
2184     /**
2185      * Returns the flags for this key event.
2186      *
2187      * @see #FLAG_WOKE_HERE
2188      */
getFlags()2189     public final int getFlags() {
2190         return mFlags;
2191     }
2192 
2193     // Mask of all modifier key meta states.  Specifically excludes locked keys like caps lock.
2194     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2195     private static final int META_MODIFIER_MASK =
2196             META_SHIFT_ON | META_SHIFT_LEFT_ON | META_SHIFT_RIGHT_ON
2197             | META_ALT_ON | META_ALT_LEFT_ON | META_ALT_RIGHT_ON
2198             | META_CTRL_ON | META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON
2199             | META_META_ON | META_META_LEFT_ON | META_META_RIGHT_ON
2200             | META_SYM_ON | META_FUNCTION_ON;
2201 
2202     // Mask of all lock key meta states.
2203     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2204     private static final int META_LOCK_MASK =
2205             META_CAPS_LOCK_ON | META_NUM_LOCK_ON | META_SCROLL_LOCK_ON;
2206 
2207     // Mask of all valid meta states.
2208     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2209     private static final int META_ALL_MASK = META_MODIFIER_MASK | META_LOCK_MASK;
2210 
2211     // Mask of all synthetic meta states that are reserved for API compatibility with
2212     // historical uses in MetaKeyKeyListener.
2213     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2214     private static final int META_SYNTHETIC_MASK =
2215             META_CAP_LOCKED | META_ALT_LOCKED | META_SYM_LOCKED | META_SELECTING;
2216 
2217     // Mask of all meta states that are not valid use in specifying a modifier key.
2218     // These bits are known to be used for purposes other than specifying modifiers.
2219     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
2220     private static final int META_INVALID_MODIFIER_MASK =
2221             META_LOCK_MASK | META_SYNTHETIC_MASK;
2222 
2223     /**
2224      * Gets a mask that includes all valid modifier key meta state bits.
2225      * <p>
2226      * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2227      * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2228      * not considered modifier keys.  Consequently, the mask specifically excludes
2229      * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2230      * </p>
2231      *
2232      * @return The modifier meta state mask which is a combination of
2233      * {@link #META_SHIFT_ON}, {@link #META_SHIFT_LEFT_ON}, {@link #META_SHIFT_RIGHT_ON},
2234      * {@link #META_ALT_ON}, {@link #META_ALT_LEFT_ON}, {@link #META_ALT_RIGHT_ON},
2235      * {@link #META_CTRL_ON}, {@link #META_CTRL_LEFT_ON}, {@link #META_CTRL_RIGHT_ON},
2236      * {@link #META_META_ON}, {@link #META_META_LEFT_ON}, {@link #META_META_RIGHT_ON},
2237      * {@link #META_SYM_ON}, {@link #META_FUNCTION_ON}.
2238      */
getModifierMetaStateMask()2239     public static int getModifierMetaStateMask() {
2240         return META_MODIFIER_MASK;
2241     }
2242 
2243     /**
2244      * Returns true if this key code is a modifier key.
2245      * <p>
2246      * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2247      * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2248      * not considered modifier keys.  Consequently, this function return false
2249      * for those keys.
2250      * </p>
2251      *
2252      * @return True if the key code is one of
2253      * {@link #KEYCODE_SHIFT_LEFT} {@link #KEYCODE_SHIFT_RIGHT},
2254      * {@link #KEYCODE_ALT_LEFT}, {@link #KEYCODE_ALT_RIGHT},
2255      * {@link #KEYCODE_CTRL_LEFT}, {@link #KEYCODE_CTRL_RIGHT},
2256      * {@link #KEYCODE_META_LEFT}, or {@link #KEYCODE_META_RIGHT},
2257      * {@link #KEYCODE_SYM}, {@link #KEYCODE_NUM}, {@link #KEYCODE_FUNCTION}.
2258      */
isModifierKey(int keyCode)2259     public static boolean isModifierKey(int keyCode) {
2260         switch (keyCode) {
2261             case KEYCODE_SHIFT_LEFT:
2262             case KEYCODE_SHIFT_RIGHT:
2263             case KEYCODE_ALT_LEFT:
2264             case KEYCODE_ALT_RIGHT:
2265             case KEYCODE_CTRL_LEFT:
2266             case KEYCODE_CTRL_RIGHT:
2267             case KEYCODE_META_LEFT:
2268             case KEYCODE_META_RIGHT:
2269             case KEYCODE_SYM:
2270             case KEYCODE_NUM:
2271             case KEYCODE_FUNCTION:
2272                 return true;
2273             default:
2274                 return false;
2275         }
2276     }
2277 
2278     /**
2279      * Normalizes the specified meta state.
2280      * <p>
2281      * The meta state is normalized such that if either the left or right modifier meta state
2282      * bits are set then the result will also include the universal bit for that modifier.
2283      * </p><p>
2284      * If the specified meta state contains {@link #META_ALT_LEFT_ON} then
2285      * the result will also contain {@link #META_ALT_ON} in addition to {@link #META_ALT_LEFT_ON}
2286      * and the other bits that were specified in the input.  The same is process is
2287      * performed for shift, control and meta.
2288      * </p><p>
2289      * If the specified meta state contains synthetic meta states defined by
2290      * {@link MetaKeyKeyListener}, then those states are translated here and the original
2291      * synthetic meta states are removed from the result.
2292      * {@link MetaKeyKeyListener#META_CAP_LOCKED} is translated to {@link #META_CAPS_LOCK_ON}.
2293      * {@link MetaKeyKeyListener#META_ALT_LOCKED} is translated to {@link #META_ALT_ON}.
2294      * {@link MetaKeyKeyListener#META_SYM_LOCKED} is translated to {@link #META_SYM_ON}.
2295      * </p><p>
2296      * Undefined meta state bits are removed.
2297      * </p>
2298      *
2299      * @param metaState The meta state.
2300      * @return The normalized meta state.
2301      */
normalizeMetaState(int metaState)2302     public static int normalizeMetaState(int metaState) {
2303         if ((metaState & (META_SHIFT_LEFT_ON | META_SHIFT_RIGHT_ON)) != 0) {
2304             metaState |= META_SHIFT_ON;
2305         }
2306         if ((metaState & (META_ALT_LEFT_ON | META_ALT_RIGHT_ON)) != 0) {
2307             metaState |= META_ALT_ON;
2308         }
2309         if ((metaState & (META_CTRL_LEFT_ON | META_CTRL_RIGHT_ON)) != 0) {
2310             metaState |= META_CTRL_ON;
2311         }
2312         if ((metaState & (META_META_LEFT_ON | META_META_RIGHT_ON)) != 0) {
2313             metaState |= META_META_ON;
2314         }
2315         if ((metaState & MetaKeyKeyListener.META_CAP_LOCKED) != 0) {
2316             metaState |= META_CAPS_LOCK_ON;
2317         }
2318         if ((metaState & MetaKeyKeyListener.META_ALT_LOCKED) != 0) {
2319             metaState |= META_ALT_ON;
2320         }
2321         if ((metaState & MetaKeyKeyListener.META_SYM_LOCKED) != 0) {
2322             metaState |= META_SYM_ON;
2323         }
2324         return metaState & META_ALL_MASK;
2325     }
2326 
2327     /**
2328      * Returns true if no modifiers keys are pressed according to the specified meta state.
2329      * <p>
2330      * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2331      * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2332      * not considered modifier keys.  Consequently, this function ignores
2333      * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2334      * </p><p>
2335      * The meta state is normalized prior to comparison using {@link #normalizeMetaState(int)}.
2336      * </p>
2337      *
2338      * @param metaState The meta state to consider.
2339      * @return True if no modifier keys are pressed.
2340      * @see #hasNoModifiers()
2341      */
metaStateHasNoModifiers(int metaState)2342     public static boolean metaStateHasNoModifiers(int metaState) {
2343         return (normalizeMetaState(metaState) & META_MODIFIER_MASK) == 0;
2344     }
2345 
2346     /**
2347      * Returns true if only the specified modifier keys are pressed according to
2348      * the specified meta state.  Returns false if a different combination of modifier
2349      * keys are pressed.
2350      * <p>
2351      * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2352      * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2353      * not considered modifier keys.  Consequently, this function ignores
2354      * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2355      * </p><p>
2356      * If the specified modifier mask includes directional modifiers, such as
2357      * {@link #META_SHIFT_LEFT_ON}, then this method ensures that the
2358      * modifier is pressed on that side.
2359      * If the specified modifier mask includes non-directional modifiers, such as
2360      * {@link #META_SHIFT_ON}, then this method ensures that the modifier
2361      * is pressed on either side.
2362      * If the specified modifier mask includes both directional and non-directional modifiers
2363      * for the same type of key, such as {@link #META_SHIFT_ON} and {@link #META_SHIFT_LEFT_ON},
2364      * then this method throws an illegal argument exception.
2365      * </p>
2366      *
2367      * @param metaState The meta state to consider.
2368      * @param modifiers The meta state of the modifier keys to check.  May be a combination
2369      * of modifier meta states as defined by {@link #getModifierMetaStateMask()}.  May be 0 to
2370      * ensure that no modifier keys are pressed.
2371      * @return True if only the specified modifier keys are pressed.
2372      * @throws IllegalArgumentException if the modifiers parameter contains invalid modifiers
2373      * @see #hasModifiers
2374      */
metaStateHasModifiers(int metaState, int modifiers)2375     public static boolean metaStateHasModifiers(int metaState, int modifiers) {
2376         // Note: For forward compatibility, we allow the parameter to contain meta states
2377         //       that we do not recognize but we explicitly disallow meta states that
2378         //       are not valid modifiers.
2379         if ((modifiers & META_INVALID_MODIFIER_MASK) != 0) {
2380             throw new IllegalArgumentException("modifiers must not contain "
2381                     + "META_CAPS_LOCK_ON, META_NUM_LOCK_ON, META_SCROLL_LOCK_ON, "
2382                     + "META_CAP_LOCKED, META_ALT_LOCKED, META_SYM_LOCKED, "
2383                     + "or META_SELECTING");
2384         }
2385 
2386         metaState = normalizeMetaState(metaState) & META_MODIFIER_MASK;
2387         metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
2388                 META_SHIFT_ON, META_SHIFT_LEFT_ON, META_SHIFT_RIGHT_ON);
2389         metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
2390                 META_ALT_ON, META_ALT_LEFT_ON, META_ALT_RIGHT_ON);
2391         metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
2392                 META_CTRL_ON, META_CTRL_LEFT_ON, META_CTRL_RIGHT_ON);
2393         metaState = metaStateFilterDirectionalModifiers(metaState, modifiers,
2394                 META_META_ON, META_META_LEFT_ON, META_META_RIGHT_ON);
2395         return metaState == modifiers;
2396     }
2397 
metaStateFilterDirectionalModifiers(int metaState, int modifiers, int basic, int left, int right)2398     private static int metaStateFilterDirectionalModifiers(int metaState,
2399             int modifiers, int basic, int left, int right) {
2400         final boolean wantBasic = (modifiers & basic) != 0;
2401         final int directional = left | right;
2402         final boolean wantLeftOrRight = (modifiers & directional) != 0;
2403 
2404         if (wantBasic) {
2405             if (wantLeftOrRight) {
2406                 throw new IllegalArgumentException("modifiers must not contain "
2407                         + metaStateToString(basic) + " combined with "
2408                         + metaStateToString(left) + " or " + metaStateToString(right));
2409             }
2410             return metaState & ~directional;
2411         } else if (wantLeftOrRight) {
2412             return metaState & ~basic;
2413         } else {
2414             return metaState;
2415         }
2416     }
2417 
2418     /**
2419      * Returns true if no modifier keys are pressed.
2420      * <p>
2421      * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2422      * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2423      * not considered modifier keys.  Consequently, this function ignores
2424      * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2425      * </p><p>
2426      * The meta state is normalized prior to comparison using {@link #normalizeMetaState(int)}.
2427      * </p>
2428      *
2429      * @return True if no modifier keys are pressed.
2430      * @see #metaStateHasNoModifiers
2431      */
hasNoModifiers()2432     public final boolean hasNoModifiers() {
2433         return metaStateHasNoModifiers(mMetaState);
2434     }
2435 
2436     /**
2437      * Returns true if only the specified modifiers keys are pressed.
2438      * Returns false if a different combination of modifier keys are pressed.
2439      * <p>
2440      * For the purposes of this function, {@link #KEYCODE_CAPS_LOCK},
2441      * {@link #KEYCODE_SCROLL_LOCK}, and {@link #KEYCODE_NUM_LOCK} are
2442      * not considered modifier keys.  Consequently, this function ignores
2443      * {@link #META_CAPS_LOCK_ON}, {@link #META_SCROLL_LOCK_ON} and {@link #META_NUM_LOCK_ON}.
2444      * </p><p>
2445      * If the specified modifier mask includes directional modifiers, such as
2446      * {@link #META_SHIFT_LEFT_ON}, then this method ensures that the
2447      * modifier is pressed on that side.
2448      * If the specified modifier mask includes non-directional modifiers, such as
2449      * {@link #META_SHIFT_ON}, then this method ensures that the modifier
2450      * is pressed on either side.
2451      * If the specified modifier mask includes both directional and non-directional modifiers
2452      * for the same type of key, such as {@link #META_SHIFT_ON} and {@link #META_SHIFT_LEFT_ON},
2453      * then this method throws an illegal argument exception.
2454      * </p>
2455      *
2456      * @param modifiers The meta state of the modifier keys to check.  May be a combination
2457      * of modifier meta states as defined by {@link #getModifierMetaStateMask()}.  May be 0 to
2458      * ensure that no modifier keys are pressed.
2459      * @return True if only the specified modifier keys are pressed.
2460      * @throws IllegalArgumentException if the modifiers parameter contains invalid modifiers
2461      * @see #metaStateHasModifiers
2462      */
hasModifiers(int modifiers)2463     public final boolean hasModifiers(int modifiers) {
2464         return metaStateHasModifiers(mMetaState, modifiers);
2465     }
2466 
2467     /**
2468      * <p>Returns the pressed state of the ALT meta key.</p>
2469      *
2470      * @return true if the ALT key is pressed, false otherwise
2471      *
2472      * @see #KEYCODE_ALT_LEFT
2473      * @see #KEYCODE_ALT_RIGHT
2474      * @see #META_ALT_ON
2475      */
isAltPressed()2476     public final boolean isAltPressed() {
2477         return (mMetaState & META_ALT_ON) != 0;
2478     }
2479 
2480     /**
2481      * <p>Returns the pressed state of the SHIFT meta key.</p>
2482      *
2483      * @return true if the SHIFT key is pressed, false otherwise
2484      *
2485      * @see #KEYCODE_SHIFT_LEFT
2486      * @see #KEYCODE_SHIFT_RIGHT
2487      * @see #META_SHIFT_ON
2488      */
isShiftPressed()2489     public final boolean isShiftPressed() {
2490         return (mMetaState & META_SHIFT_ON) != 0;
2491     }
2492 
2493     /**
2494      * <p>Returns the pressed state of the SYM meta key.</p>
2495      *
2496      * @return true if the SYM key is pressed, false otherwise
2497      *
2498      * @see #KEYCODE_SYM
2499      * @see #META_SYM_ON
2500      */
isSymPressed()2501     public final boolean isSymPressed() {
2502         return (mMetaState & META_SYM_ON) != 0;
2503     }
2504 
2505     /**
2506      * <p>Returns the pressed state of the CTRL meta key.</p>
2507      *
2508      * @return true if the CTRL key is pressed, false otherwise
2509      *
2510      * @see #KEYCODE_CTRL_LEFT
2511      * @see #KEYCODE_CTRL_RIGHT
2512      * @see #META_CTRL_ON
2513      */
isCtrlPressed()2514     public final boolean isCtrlPressed() {
2515         return (mMetaState & META_CTRL_ON) != 0;
2516     }
2517 
2518     /**
2519      * <p>Returns the pressed state of the META meta key.</p>
2520      *
2521      * @return true if the META key is pressed, false otherwise
2522      *
2523      * @see #KEYCODE_META_LEFT
2524      * @see #KEYCODE_META_RIGHT
2525      * @see #META_META_ON
2526      */
isMetaPressed()2527     public final boolean isMetaPressed() {
2528         return (mMetaState & META_META_ON) != 0;
2529     }
2530 
2531     /**
2532      * <p>Returns the pressed state of the FUNCTION meta key.</p>
2533      *
2534      * @return true if the FUNCTION key is pressed, false otherwise
2535      *
2536      * @see #KEYCODE_FUNCTION
2537      * @see #META_FUNCTION_ON
2538      */
isFunctionPressed()2539     public final boolean isFunctionPressed() {
2540         return (mMetaState & META_FUNCTION_ON) != 0;
2541     }
2542 
2543     /**
2544      * <p>Returns the locked state of the CAPS LOCK meta key.</p>
2545      *
2546      * @return true if the CAPS LOCK key is on, false otherwise
2547      *
2548      * @see #KEYCODE_CAPS_LOCK
2549      * @see #META_CAPS_LOCK_ON
2550      */
isCapsLockOn()2551     public final boolean isCapsLockOn() {
2552         return (mMetaState & META_CAPS_LOCK_ON) != 0;
2553     }
2554 
2555     /**
2556      * <p>Returns the locked state of the NUM LOCK meta key.</p>
2557      *
2558      * @return true if the NUM LOCK key is on, false otherwise
2559      *
2560      * @see #KEYCODE_NUM_LOCK
2561      * @see #META_NUM_LOCK_ON
2562      */
isNumLockOn()2563     public final boolean isNumLockOn() {
2564         return (mMetaState & META_NUM_LOCK_ON) != 0;
2565     }
2566 
2567     /**
2568      * <p>Returns the locked state of the SCROLL LOCK meta key.</p>
2569      *
2570      * @return true if the SCROLL LOCK key is on, false otherwise
2571      *
2572      * @see #KEYCODE_SCROLL_LOCK
2573      * @see #META_SCROLL_LOCK_ON
2574      */
isScrollLockOn()2575     public final boolean isScrollLockOn() {
2576         return (mMetaState & META_SCROLL_LOCK_ON) != 0;
2577     }
2578 
2579     /**
2580      * Retrieve the action of this key event.  May be either
2581      * {@link #ACTION_DOWN}, {@link #ACTION_UP}, or {@link #ACTION_MULTIPLE}.
2582      *
2583      * @return The event action: ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
2584      */
getAction()2585     public final int getAction() {
2586         return mAction;
2587     }
2588 
2589     /**
2590      * For {@link #ACTION_UP} events, indicates that the event has been
2591      * canceled as per {@link #FLAG_CANCELED}.
2592      */
isCanceled()2593     public final boolean isCanceled() {
2594         return (mFlags&FLAG_CANCELED) != 0;
2595     }
2596 
2597     /**
2598      * Set {@link #FLAG_CANCELED} flag for the key event.
2599      *
2600      * @hide
2601      */
2602     @Override
cancel()2603     public final void cancel() {
2604         mFlags |= FLAG_CANCELED;
2605     }
2606 
2607     /**
2608      * Call this during {@link Callback#onKeyDown} to have the system track
2609      * the key through its final up (possibly including a long press).  Note
2610      * that only one key can be tracked at a time -- if another key down
2611      * event is received while a previous one is being tracked, tracking is
2612      * stopped on the previous event.
2613      */
startTracking()2614     public final void startTracking() {
2615         mFlags |= FLAG_START_TRACKING;
2616     }
2617 
2618     /**
2619      * For {@link #ACTION_UP} events, indicates that the event is still being
2620      * tracked from its initial down event as per
2621      * {@link #FLAG_TRACKING}.
2622      */
isTracking()2623     public final boolean isTracking() {
2624         return (mFlags&FLAG_TRACKING) != 0;
2625     }
2626 
2627     /**
2628      * For {@link #ACTION_DOWN} events, indicates that the event has been
2629      * canceled as per {@link #FLAG_LONG_PRESS}.
2630      */
isLongPress()2631     public final boolean isLongPress() {
2632         return (mFlags&FLAG_LONG_PRESS) != 0;
2633     }
2634 
2635     /**
2636      * Retrieve the key code of the key event.  This is the physical key that
2637      * was pressed, <em>not</em> the Unicode character.
2638      *
2639      * @return The key code of the event.
2640      */
getKeyCode()2641     public final int getKeyCode() {
2642         return mKeyCode;
2643     }
2644 
2645     /**
2646      * For the special case of a {@link #ACTION_MULTIPLE} event with key
2647      * code of {@link #KEYCODE_UNKNOWN}, this is a raw string of characters
2648      * associated with the event.  In all other cases it is null.
2649      *
2650      * @return Returns a String of 1 or more characters associated with
2651      * the event.
2652      *
2653      * @deprecated no longer used by the input system.
2654      */
2655     @Deprecated
getCharacters()2656     public final String getCharacters() {
2657         return mCharacters;
2658     }
2659 
2660     /**
2661      * Retrieve the hardware key id of this key event.  These values are not
2662      * reliable and vary from device to device.
2663      *
2664      * {@more}
2665      * Mostly this is here for debugging purposes.
2666      */
getScanCode()2667     public final int getScanCode() {
2668         return mScanCode;
2669     }
2670 
2671     /**
2672      * Retrieve the repeat count of the event.  For key down events,
2673      * this is the number of times the key has repeated with the first
2674      * down starting at 0 and counting up from there.  For key up events,
2675      * this is always equal to zero. For multiple key events,
2676      * this is the number of down/up pairs that have occurred.
2677      *
2678      * @return The number of times the key has repeated.
2679      */
getRepeatCount()2680     public final int getRepeatCount() {
2681         return mRepeatCount;
2682     }
2683 
2684     /**
2685      * Modifies the down time and the event time of the event.
2686      *
2687      * @param downTime The new down time (in {@link android.os.SystemClock#uptimeMillis}) of the
2688      *                 event.
2689      * @param eventTime The new event time (in {@link android.os.SystemClock#uptimeMillis}) of the
2690      *                  event.
2691      * @hide
2692      */
setTime(long downTime, long eventTime)2693     public final void setTime(long downTime, long eventTime) {
2694         mDownTime = TimeUnit.NANOSECONDS.convert(downTime, TimeUnit.MILLISECONDS);
2695         mEventTime = TimeUnit.NANOSECONDS.convert(eventTime, TimeUnit.MILLISECONDS);
2696     }
2697 
2698     /**
2699      * Retrieve the time of the most recent key down event,
2700      * in the {@link android.os.SystemClock#uptimeMillis} time base.  If this
2701      * is a down event, this will be the same as {@link #getEventTime()}.
2702      * Note that when chording keys, this value is the down time of the
2703      * most recently pressed key, which may <em>not</em> be the same physical
2704      * key of this event.
2705      *
2706      * @return Returns the most recent key down time, in the
2707      * {@link android.os.SystemClock#uptimeMillis} time base
2708      */
getDownTime()2709     public final long getDownTime() {
2710         return TimeUnit.MILLISECONDS.convert(mDownTime, TimeUnit.NANOSECONDS);
2711     }
2712 
2713     /**
2714      * Retrieve the time this event occurred,
2715      * in the {@link android.os.SystemClock#uptimeMillis} time base.
2716      *
2717      * @return Returns the time this event occurred,
2718      * in the {@link android.os.SystemClock#uptimeMillis} time base.
2719      */
2720     @Override
getEventTime()2721     public final long getEventTime() {
2722         return TimeUnit.MILLISECONDS.convert(mEventTime, TimeUnit.NANOSECONDS);
2723     }
2724 
2725     /**
2726      * Retrieve the time this event occurred,
2727      * in the {@link android.os.SystemClock#uptimeMillis} time base but with
2728      * nanosecond (instead of millisecond) precision.
2729      * <p>
2730      * The value is in nanosecond precision but it may not have nanosecond accuracy.
2731      * </p>
2732      *
2733      * @return Returns the time this event occurred,
2734      * in the {@link android.os.SystemClock#uptimeMillis} time base but with
2735      * nanosecond (instead of millisecond) precision.
2736      *
2737      * @hide
2738      */
2739     @Override
getEventTimeNanos()2740     public final long getEventTimeNanos() {
2741         return mEventTime;
2742     }
2743 
2744     /**
2745      * Renamed to {@link #getDeviceId}.
2746      *
2747      * @hide
2748      * @deprecated use {@link #getDeviceId()} instead.
2749      */
2750     @Deprecated
getKeyboardDevice()2751     public final int getKeyboardDevice() {
2752         return mDeviceId;
2753     }
2754 
2755     /**
2756      * Gets the {@link KeyCharacterMap} associated with the keyboard device.
2757      *
2758      * @return The associated key character map.
2759      * @throws {@link KeyCharacterMap.UnavailableException} if the key character map
2760      * could not be loaded because it was malformed or the default key character map
2761      * is missing from the system.
2762      *
2763      * @see KeyCharacterMap#load
2764      */
getKeyCharacterMap()2765     public final KeyCharacterMap getKeyCharacterMap() {
2766         return KeyCharacterMap.load(mDeviceId);
2767     }
2768 
2769     /**
2770      * Gets the primary character for this key.
2771      * In other words, the label that is physically printed on it.
2772      *
2773      * @return The display label character, or 0 if none (eg. for non-printing keys).
2774      */
getDisplayLabel()2775     public char getDisplayLabel() {
2776         return getKeyCharacterMap().getDisplayLabel(mKeyCode);
2777     }
2778 
2779     /**
2780      * Gets the Unicode character generated by the specified key and meta
2781      * key state combination.
2782      * <p>
2783      * Returns the Unicode character that the specified key would produce
2784      * when the specified meta bits (see {@link MetaKeyKeyListener})
2785      * were active.
2786      * </p><p>
2787      * Returns 0 if the key is not one that is used to type Unicode
2788      * characters.
2789      * </p><p>
2790      * If the return value has bit {@link KeyCharacterMap#COMBINING_ACCENT} set, the
2791      * key is a "dead key" that should be combined with another to
2792      * actually produce a character -- see {@link KeyCharacterMap#getDeadChar} --
2793      * after masking with {@link KeyCharacterMap#COMBINING_ACCENT_MASK}.
2794      * </p>
2795      *
2796      * @return The associated character or combining accent, or 0 if none.
2797      */
getUnicodeChar()2798     public int getUnicodeChar() {
2799         return getUnicodeChar(mMetaState);
2800     }
2801 
2802     /**
2803      * Gets the Unicode character generated by the specified key and meta
2804      * key state combination.
2805      * <p>
2806      * Returns the Unicode character that the specified key would produce
2807      * when the specified meta bits (see {@link MetaKeyKeyListener})
2808      * were active.
2809      * </p><p>
2810      * Returns 0 if the key is not one that is used to type Unicode
2811      * characters.
2812      * </p><p>
2813      * If the return value has bit {@link KeyCharacterMap#COMBINING_ACCENT} set, the
2814      * key is a "dead key" that should be combined with another to
2815      * actually produce a character -- see {@link KeyCharacterMap#getDeadChar} --
2816      * after masking with {@link KeyCharacterMap#COMBINING_ACCENT_MASK}.
2817      * </p>
2818      *
2819      * @param metaState The meta key modifier state.
2820      * @return The associated character or combining accent, or 0 if none.
2821      */
getUnicodeChar(int metaState)2822     public int getUnicodeChar(int metaState) {
2823         return getKeyCharacterMap().get(mKeyCode, metaState);
2824     }
2825 
2826     /**
2827      * Get the character conversion data for a given key code.
2828      *
2829      * @param results A {@link KeyCharacterMap.KeyData} instance that will be
2830      * filled with the results.
2831      * @return True if the key was mapped.  If the key was not mapped, results is not modified.
2832      *
2833      * @deprecated instead use {@link #getDisplayLabel()},
2834      * {@link #getNumber()} or {@link #getUnicodeChar(int)}.
2835      */
2836     @Deprecated
getKeyData(KeyData results)2837     public boolean getKeyData(KeyData results) {
2838         return getKeyCharacterMap().getKeyData(mKeyCode, results);
2839     }
2840 
2841     /**
2842      * Gets the first character in the character array that can be generated
2843      * by the specified key code.
2844      * <p>
2845      * This is a convenience function that returns the same value as
2846      * {@link #getMatch(char[],int) getMatch(chars, 0)}.
2847      * </p>
2848      *
2849      * @param chars The array of matching characters to consider.
2850      * @return The matching associated character, or 0 if none.
2851      */
getMatch(char[] chars)2852     public char getMatch(char[] chars) {
2853         return getMatch(chars, 0);
2854     }
2855 
2856     /**
2857      * Gets the first character in the character array that can be generated
2858      * by the specified key code.  If there are multiple choices, prefers
2859      * the one that would be generated with the specified meta key modifier state.
2860      *
2861      * @param chars The array of matching characters to consider.
2862      * @param metaState The preferred meta key modifier state.
2863      * @return The matching associated character, or 0 if none.
2864      */
getMatch(char[] chars, int metaState)2865     public char getMatch(char[] chars, int metaState) {
2866         return getKeyCharacterMap().getMatch(mKeyCode, chars, metaState);
2867     }
2868 
2869     /**
2870      * Gets the number or symbol associated with the key.
2871      * <p>
2872      * The character value is returned, not the numeric value.
2873      * If the key is not a number, but is a symbol, the symbol is retuned.
2874      * </p><p>
2875      * This method is intended to to support dial pads and other numeric or
2876      * symbolic entry on keyboards where certain keys serve dual function
2877      * as alphabetic and symbolic keys.  This method returns the number
2878      * or symbol associated with the key independent of whether the user
2879      * has pressed the required modifier.
2880      * </p><p>
2881      * For example, on one particular keyboard the keys on the top QWERTY row generate
2882      * numbers when ALT is pressed such that ALT-Q maps to '1'.  So for that keyboard
2883      * when {@link #getNumber} is called with {@link KeyEvent#KEYCODE_Q} it returns '1'
2884      * so that the user can type numbers without pressing ALT when it makes sense.
2885      * </p>
2886      *
2887      * @return The associated numeric or symbolic character, or 0 if none.
2888      */
getNumber()2889     public char getNumber() {
2890         return getKeyCharacterMap().getNumber(mKeyCode);
2891     }
2892 
2893     /**
2894      * Returns true if this key produces a glyph.
2895      *
2896      * @return True if the key is a printing key.
2897      */
isPrintingKey()2898     public boolean isPrintingKey() {
2899         return getKeyCharacterMap().isPrintingKey(mKeyCode);
2900     }
2901 
2902     /**
2903      * @deprecated Use {@link #dispatch(Callback, DispatcherState, Object)} instead.
2904      */
2905     @Deprecated
dispatch(Callback receiver)2906     public final boolean dispatch(Callback receiver) {
2907         return dispatch(receiver, null, null);
2908     }
2909 
2910     /**
2911      * Deliver this key event to a {@link Callback} interface.  If this is
2912      * an ACTION_MULTIPLE event and it is not handled, then an attempt will
2913      * be made to deliver a single normal event.
2914      *
2915      * @param receiver The Callback that will be given the event.
2916      * @param state State information retained across events.
2917      * @param target The target of the dispatch, for use in tracking.
2918      *
2919      * @return The return value from the Callback method that was called.
2920      */
dispatch(Callback receiver, DispatcherState state, Object target)2921     public final boolean dispatch(Callback receiver, DispatcherState state,
2922             Object target) {
2923         switch (mAction) {
2924             case ACTION_DOWN: {
2925                 mFlags &= ~FLAG_START_TRACKING;
2926                 if (DEBUG) Log.v(TAG, "Key down to " + target + " in " + state
2927                         + ": " + this);
2928                 boolean res = receiver.onKeyDown(mKeyCode, this);
2929                 if (state != null) {
2930                     if (res && mRepeatCount == 0 && (mFlags&FLAG_START_TRACKING) != 0) {
2931                         if (DEBUG) Log.v(TAG, "  Start tracking!");
2932                         state.startTracking(this, target);
2933                     } else if (isLongPress() && state.isTracking(this)) {
2934                         try {
2935                             if (receiver.onKeyLongPress(mKeyCode, this)) {
2936                                 if (DEBUG) Log.v(TAG, "  Clear from long press!");
2937                                 state.performedLongPress(this);
2938                                 res = true;
2939                             }
2940                         } catch (AbstractMethodError e) {
2941                         }
2942                     }
2943                 }
2944                 return res;
2945             }
2946             case ACTION_UP:
2947                 if (DEBUG) Log.v(TAG, "Key up to " + target + " in " + state
2948                         + ": " + this);
2949                 if (state != null) {
2950                     state.handleUpEvent(this);
2951                 }
2952                 return receiver.onKeyUp(mKeyCode, this);
2953             case ACTION_MULTIPLE:
2954                 final int count = mRepeatCount;
2955                 final int code = mKeyCode;
2956                 if (receiver.onKeyMultiple(code, count, this)) {
2957                     return true;
2958                 }
2959                 if (code != KeyEvent.KEYCODE_UNKNOWN) {
2960                     mAction = ACTION_DOWN;
2961                     mRepeatCount = 0;
2962                     boolean handled = receiver.onKeyDown(code, this);
2963                     if (handled) {
2964                         mAction = ACTION_UP;
2965                         receiver.onKeyUp(code, this);
2966                     }
2967                     mAction = ACTION_MULTIPLE;
2968                     mRepeatCount = count;
2969                     return handled;
2970                 }
2971                 return false;
2972         }
2973         return false;
2974     }
2975 
2976     /**
2977      * Use with {@link KeyEvent#dispatch(Callback, DispatcherState, Object)}
2978      * for more advanced key dispatching, such as long presses.
2979      */
2980     public static class DispatcherState {
2981         int mDownKeyCode;
2982         Object mDownTarget;
2983         SparseIntArray mActiveLongPresses = new SparseIntArray();
2984 
2985         /**
2986          * Reset back to initial state.
2987          */
reset()2988         public void reset() {
2989             if (DEBUG) Log.v(TAG, "Reset: " + this);
2990             mDownKeyCode = 0;
2991             mDownTarget = null;
2992             mActiveLongPresses.clear();
2993         }
2994 
2995         /**
2996          * Stop any tracking associated with this target.
2997          */
reset(Object target)2998         public void reset(Object target) {
2999             if (mDownTarget == target) {
3000                 if (DEBUG) Log.v(TAG, "Reset in " + target + ": " + this);
3001                 mDownKeyCode = 0;
3002                 mDownTarget = null;
3003             }
3004         }
3005 
3006         /**
3007          * Start tracking the key code associated with the given event.  This
3008          * can only be called on a key down.  It will allow you to see any
3009          * long press associated with the key, and will result in
3010          * {@link KeyEvent#isTracking} return true on the long press and up
3011          * events.
3012          *
3013          * <p>This is only needed if you are directly dispatching events, rather
3014          * than handling them in {@link Callback#onKeyDown}.
3015          */
startTracking(KeyEvent event, Object target)3016         public void startTracking(KeyEvent event, Object target) {
3017             if (event.getAction() != ACTION_DOWN) {
3018                 throw new IllegalArgumentException(
3019                         "Can only start tracking on a down event");
3020             }
3021             if (DEBUG) Log.v(TAG, "Start trackingt in " + target + ": " + this);
3022             mDownKeyCode = event.getKeyCode();
3023             mDownTarget = target;
3024         }
3025 
3026         /**
3027          * Return true if the key event is for a key code that is currently
3028          * being tracked by the dispatcher.
3029          */
isTracking(KeyEvent event)3030         public boolean isTracking(KeyEvent event) {
3031             return mDownKeyCode == event.getKeyCode();
3032         }
3033 
3034         /**
3035          * Keep track of the given event's key code as having performed an
3036          * action with a long press, so no action should occur on the up.
3037          * <p>This is only needed if you are directly dispatching events, rather
3038          * than handling them in {@link Callback#onKeyLongPress}.
3039          */
performedLongPress(KeyEvent event)3040         public void performedLongPress(KeyEvent event) {
3041             mActiveLongPresses.put(event.getKeyCode(), 1);
3042         }
3043 
3044         /**
3045          * Handle key up event to stop tracking.  This resets the dispatcher state,
3046          * and updates the key event state based on it.
3047          * <p>This is only needed if you are directly dispatching events, rather
3048          * than handling them in {@link Callback#onKeyUp}.
3049          */
handleUpEvent(KeyEvent event)3050         public void handleUpEvent(KeyEvent event) {
3051             final int keyCode = event.getKeyCode();
3052             if (DEBUG) Log.v(TAG, "Handle key up " + event + ": " + this);
3053             int index = mActiveLongPresses.indexOfKey(keyCode);
3054             if (index >= 0) {
3055                 if (DEBUG) Log.v(TAG, "  Index: " + index);
3056                 event.mFlags |= FLAG_CANCELED | FLAG_CANCELED_LONG_PRESS;
3057                 mActiveLongPresses.removeAt(index);
3058             }
3059             if (mDownKeyCode == keyCode) {
3060                 if (DEBUG) Log.v(TAG, "  Tracking!");
3061                 event.mFlags |= FLAG_TRACKING;
3062                 mDownKeyCode = 0;
3063                 mDownTarget = null;
3064             }
3065         }
3066     }
3067 
3068     @Override
toString()3069     public String toString() {
3070         StringBuilder msg = new StringBuilder();
3071         msg.append("KeyEvent { action=").append(actionToString(mAction));
3072         msg.append(", keyCode=").append(keyCodeToString(mKeyCode));
3073         msg.append(", scanCode=").append(mScanCode);
3074         if (mCharacters != null) {
3075             msg.append(", characters=\"").append(mCharacters).append("\"");
3076         }
3077         msg.append(", metaState=").append(metaStateToString(mMetaState));
3078         msg.append(", flags=0x").append(Integer.toHexString(mFlags));
3079         msg.append(", repeatCount=").append(mRepeatCount);
3080         msg.append(", eventTime=").append(mEventTime);
3081         msg.append(", downTime=").append(mDownTime);
3082         msg.append(", deviceId=").append(mDeviceId);
3083         msg.append(", source=0x").append(Integer.toHexString(mSource));
3084         msg.append(", displayId=").append(mDisplayId);
3085         msg.append(" }");
3086         return msg.toString();
3087     }
3088 
3089     /**
3090      * Returns a string that represents the symbolic name of the specified action
3091      * such as "ACTION_DOWN", or an equivalent numeric constant such as "35" if unknown.
3092      *
3093      * @param action The action.
3094      * @return The symbolic name of the specified action.
3095      * @hide
3096      */
3097     @TestApi
actionToString(int action)3098     public static String actionToString(int action) {
3099         switch (action) {
3100             case ACTION_DOWN:
3101                 return "ACTION_DOWN";
3102             case ACTION_UP:
3103                 return "ACTION_UP";
3104             case ACTION_MULTIPLE:
3105                 return "ACTION_MULTIPLE";
3106             default:
3107                 return Integer.toString(action);
3108         }
3109     }
3110 
3111     /**
3112      * Returns a string that represents the symbolic name of the specified keycode
3113      * such as "KEYCODE_A", "KEYCODE_DPAD_UP", or an equivalent numeric constant
3114      * such as "1001" if unknown.
3115      *
3116      * This function is intended to be used mostly for debugging, logging, and testing. It is not
3117      * locale-specific and is not intended to be used in a user-facing manner.
3118      *
3119      * @param keyCode The key code.
3120      * @return The symbolic name of the specified keycode.
3121      *
3122      * @see KeyCharacterMap#getDisplayLabel
3123      */
keyCodeToString(int keyCode)3124     public static String keyCodeToString(int keyCode) {
3125         String symbolicName = nativeKeyCodeToString(keyCode);
3126         return symbolicName != null ? LABEL_PREFIX + symbolicName : Integer.toString(keyCode);
3127     }
3128 
3129     /**
3130      * Gets a keycode by its symbolic name such as "KEYCODE_A" or an equivalent
3131      * numeric constant such as "29". For symbolic names,
3132      * starting in {@link android.os.Build.VERSION_CODES#Q} the prefix "KEYCODE_" is optional.
3133      *
3134      * @param symbolicName The symbolic name of the keycode.
3135      * @return The keycode or {@link #KEYCODE_UNKNOWN} if not found.
3136      * @see #keyCodeToString(int)
3137      */
keyCodeFromString(@onNull String symbolicName)3138     public static int keyCodeFromString(@NonNull String symbolicName) {
3139         try {
3140             int keyCode = Integer.parseInt(symbolicName);
3141             if (keyCodeIsValid(keyCode)) {
3142                 return keyCode;
3143             }
3144         } catch (NumberFormatException ex) {
3145         }
3146 
3147         if (symbolicName.startsWith(LABEL_PREFIX)) {
3148             symbolicName = symbolicName.substring(LABEL_PREFIX.length());
3149         }
3150         int keyCode = nativeKeyCodeFromString(symbolicName);
3151         if (keyCodeIsValid(keyCode)) {
3152             return keyCode;
3153         }
3154         return KEYCODE_UNKNOWN;
3155     }
3156 
keyCodeIsValid(int keyCode)3157     private static boolean keyCodeIsValid(int keyCode) {
3158         return keyCode >= KEYCODE_UNKNOWN && keyCode <= LAST_KEYCODE;
3159     }
3160 
3161     /**
3162      * Returns a string that represents the symbolic name of the specified combined meta
3163      * key modifier state flags such as "0", "META_SHIFT_ON",
3164      * "META_ALT_ON|META_SHIFT_ON" or an equivalent numeric constant such as "0x10000000"
3165      * if unknown.
3166      *
3167      * @param metaState The meta state.
3168      * @return The symbolic name of the specified combined meta state flags.
3169      * @hide
3170      */
metaStateToString(int metaState)3171     public static String metaStateToString(int metaState) {
3172         if (metaState == 0) {
3173             return "0";
3174         }
3175         StringBuilder result = null;
3176         int i = 0;
3177         while (metaState != 0) {
3178             final boolean isSet = (metaState & 1) != 0;
3179             metaState >>>= 1; // unsigned shift!
3180             if (isSet) {
3181                 final String name = META_SYMBOLIC_NAMES[i];
3182                 if (result == null) {
3183                     if (metaState == 0) {
3184                         return name;
3185                     }
3186                     result = new StringBuilder(name);
3187                 } else {
3188                     result.append('|');
3189                     result.append(name);
3190                 }
3191             }
3192             i += 1;
3193         }
3194         return result.toString();
3195     }
3196 
3197     public static final @android.annotation.NonNull Parcelable.Creator<KeyEvent> CREATOR
3198             = new Parcelable.Creator<KeyEvent>() {
3199         @Override
3200         public KeyEvent createFromParcel(Parcel in) {
3201             in.readInt(); // skip token, we already know this is a KeyEvent
3202             return KeyEvent.createFromParcelBody(in);
3203         }
3204 
3205         @Override
3206         public KeyEvent[] newArray(int size) {
3207             return new KeyEvent[size];
3208         }
3209     };
3210 
3211     /** @hide */
createFromParcelBody(Parcel in)3212     public static KeyEvent createFromParcelBody(Parcel in) {
3213         return new KeyEvent(in);
3214     }
3215 
KeyEvent(Parcel in)3216     private KeyEvent(Parcel in) {
3217         // NOTE: ideally this constructor should call the canonical one, but that would require
3218         // changing the order the fields are written to the parcel, which could break native code
3219         mId = in.readInt();
3220         mDeviceId = in.readInt();
3221         mSource = in.readInt();
3222         mDisplayId = in.readInt();
3223         mHmac = in.createByteArray();
3224         mAction = in.readInt();
3225         mKeyCode = in.readInt();
3226         mRepeatCount = in.readInt();
3227         mMetaState = in.readInt();
3228         mScanCode = in.readInt();
3229         mFlags = in.readInt();
3230         mDownTime = in.readLong();
3231         mEventTime = in.readLong();
3232         mCharacters = in.readString();
3233     }
3234 
3235     @Override
writeToParcel(Parcel out, int flags)3236     public void writeToParcel(Parcel out, int flags) {
3237         out.writeInt(PARCEL_TOKEN_KEY_EVENT);
3238 
3239         out.writeInt(mId);
3240         out.writeInt(mDeviceId);
3241         out.writeInt(mSource);
3242         out.writeInt(mDisplayId);
3243         out.writeByteArray(mHmac);
3244         out.writeInt(mAction);
3245         out.writeInt(mKeyCode);
3246         out.writeInt(mRepeatCount);
3247         out.writeInt(mMetaState);
3248         out.writeInt(mScanCode);
3249         out.writeInt(mFlags);
3250         out.writeLong(mDownTime);
3251         out.writeLong(mEventTime);
3252         out.writeString(mCharacters);
3253     }
3254 }
3255