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