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