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