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