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