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