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