Frossky 发布的文章

Wall外面:阅读原文

KeyEvent

Kotlin |Java

public class KeyEvent
extends InputEvent implements Parcelable

java.lang.Object
   ↳    android.view.InputEvent
       ↳    android.view.KeyEvent

Object used to report key and button events.

Each key press is described by a sequence of key events. A key press starts with a key event with ACTION_DOWN. If the key is held sufficiently long that it repeats, then the initial down is followed additional key events with ACTION_DOWN and a non-zero value for getRepeatCount(). The last key event is a ACTION_UP for the key up. If the key press is canceled, the key up event will have the FLAG_CANCELED flag set.

Key events are generally accompanied by a key code (getKeyCode()), scan code (getScanCode()) and meta state (getMetaState()). Key code constants are defined in this class. Scan code constants are raw device-specific codes obtained from the OS and so are not generally meaningful to applications unless interpreted using the KeyCharacterMap. Meta states describe the pressed state of key modifiers such as META_SHIFT_ON or META_ALT_ON.

Key codes typically correspond one-to-one with individual keys on an input device. Many keys and key combinations serve quite different functions on different input devices so care must be taken when interpreting them. Always use the KeyCharacterMap associated with the input device when mapping keys to characters. Be aware that there may be multiple key input devices active at the same time and each will have its own key character map.

As soft input methods can use multiple and inventive ways of inputting text, there is no guarantee that any key press on a soft keyboard will generate a key event: this is left to the IME's discretion, and in fact sending such events is discouraged. You should never rely on receiving KeyEvents for any key on a soft input method. In particular, the default software keyboard will never send any key event to any application targetting Jelly Bean or later, and will only send events for some presses of the delete and return keys to applications targetting Ice Cream Sandwich or earlier. Be aware that other software input methods may never send key events regardless of the version. Consider using editor actions like EditorInfo.IME_ACTION_DONE if you need specific interaction with the software keyboard, as it gives more visibility to the user as to how your application will react to key presses.

When interacting with an IME, the framework may deliver key events with the special action ACTION_MULTIPLE that either specifies that single repeated key code or a sequence of characters to insert.

In general, the framework cannot guarantee that the key events it delivers to a view always constitute complete key sequences since some events may be dropped or modified by containing views before they are delivered. The view implementation should be prepared to handle FLAG_CANCELED and should tolerate anomalous situations such as receiving a new ACTION_DOWN without first having received an ACTION_UP for the prior key press.

Refer to InputDevice for more information about how different kinds of input devices and sources represent keys and buttons.

Summary
Nested classes
interface KeyEvent.Callback

class KeyEvent.DispatcherState
Use with KeyEvent#dispatch(Callback, DispatcherState, Object) for more advanced key dispatching, such as long presses.

Constants
int ACTION_DOWN
getAction() value: the key has been pressed down.

int ACTION_MULTIPLE
This constant was deprecated in API level 29. No longer used by the input system. getAction() value: multiple duplicate key events have occurred in a row, or a complex string is being delivered. If the key code is not KEYCODE_UNKNOWN then the getRepeatCount() method returns the number of times the given key code should be executed. Otherwise, if the key code is KEYCODE_UNKNOWN, then this is a sequence of characters as returned by getCharacters().

int ACTION_UP
getAction() value: the key has been released.

int FLAG_CANCELED
When associated with up key events, this indicates that the key press has been canceled.

int FLAG_CANCELED_LONG_PRESS
Set when a key event has FLAG_CANCELED set because a long press action was executed while it was down.

int FLAG_EDITOR_ACTION
This mask is used for compatibility, to identify enter keys that are coming from an IME whose enter key has been auto-labelled "next" or "done".

int FLAG_FALLBACK
Set when a key event has been synthesized to implement default behavior for an event that the application did not handle.

int FLAG_FROM_SYSTEM
This mask is set if an event was known to come from a trusted part of the system.

int FLAG_KEEP_TOUCH_MODE
This mask is set if we don't want the key event to cause us to leave touch mode.

int FLAG_LONG_PRESS
This flag is set for the first key repeat that occurs after the long press timeout.

int FLAG_SOFT_KEYBOARD
This mask is set if the key event was generated by a software keyboard.

int FLAG_TRACKING
Set for ACTION_UP when this event's key code is still being tracked from its initial down.

int FLAG_VIRTUAL_HARD_KEY
This key event was generated by a virtual (on-screen) hard key area.

int FLAG_WOKE_HERE
This constant was deprecated in API level 20. This flag will never be set by the system since the system consumes all wake keys itself.

int KEYCODE_0
Key code constant: '0' key.

int KEYCODE_1
Key code constant: '1' key.

int KEYCODE_11
Key code constant: '11' key.

int KEYCODE_12
Key code constant: '12' key.

int KEYCODE_2
Key code constant: '2' key.

int KEYCODE_3
Key code constant: '3' key.

int KEYCODE_3D_MODE
Key code constant: 3D Mode key.

int KEYCODE_4
Key code constant: '4' key.

int KEYCODE_5
Key code constant: '5' key.

int KEYCODE_6
Key code constant: '6' key.

int KEYCODE_7
Key code constant: '7' key.

int KEYCODE_8
Key code constant: '8' key.

int KEYCODE_9
Key code constant: '9' key.

int KEYCODE_A
Key code constant: 'A' key.

int KEYCODE_ALL_APPS
Key code constant: Show all apps

int KEYCODE_ALT_LEFT
Key code constant: Left Alt modifier key.

int KEYCODE_ALT_RIGHT
Key code constant: Right Alt modifier key.

int KEYCODE_APOSTROPHE
Key code constant: ''' (apostrophe) key.

int KEYCODE_APP_SWITCH
Key code constant: App switch key.

int KEYCODE_ASSIST
Key code constant: Assist key.

int KEYCODE_AT
Key code constant: '@' key.

int KEYCODE_AVR_INPUT
Key code constant: A/V Receiver input key.

int KEYCODE_AVR_POWER
Key code constant: A/V Receiver power key.

int KEYCODE_B
Key code constant: 'B' key.

int KEYCODE_BACK
Key code constant: Back key.

int KEYCODE_BACKSLASH
Key code constant: '\' key.

int KEYCODE_BOOKMARK
Key code constant: Bookmark key.

int KEYCODE_BREAK
Key code constant: Break / Pause key.

int KEYCODE_BRIGHTNESS_DOWN
Key code constant: Brightness Down key.

int KEYCODE_BRIGHTNESS_UP
Key code constant: Brightness Up key.

int KEYCODE_BUTTON_1
Key code constant: Generic Game Pad Button #1.

int KEYCODE_BUTTON_10
Key code constant: Generic Game Pad Button #10.

int KEYCODE_BUTTON_11
Key code constant: Generic Game Pad Button #11.

int KEYCODE_BUTTON_12
Key code constant: Generic Game Pad Button #12.

int KEYCODE_BUTTON_13
Key code constant: Generic Game Pad Button #13.

int KEYCODE_BUTTON_14
Key code constant: Generic Game Pad Button #14.

int KEYCODE_BUTTON_15
Key code constant: Generic Game Pad Button #15.

int KEYCODE_BUTTON_16
Key code constant: Generic Game Pad Button #16.

int KEYCODE_BUTTON_2
Key code constant: Generic Game Pad Button #2.

int KEYCODE_BUTTON_3
Key code constant: Generic Game Pad Button #3.

int KEYCODE_BUTTON_4
Key code constant: Generic Game Pad Button #4.

int KEYCODE_BUTTON_5
Key code constant: Generic Game Pad Button #5.

int KEYCODE_BUTTON_6
Key code constant: Generic Game Pad Button #6.

int KEYCODE_BUTTON_7
Key code constant: Generic Game Pad Button #7.

int KEYCODE_BUTTON_8
Key code constant: Generic Game Pad Button #8.

int KEYCODE_BUTTON_9
Key code constant: Generic Game Pad Button #9.

int KEYCODE_BUTTON_A
Key code constant: A Button key.

int KEYCODE_BUTTON_B
Key code constant: B Button key.

int KEYCODE_BUTTON_C
Key code constant: C Button key.

int KEYCODE_BUTTON_L1
Key code constant: L1 Button key.

int KEYCODE_BUTTON_L2
Key code constant: L2 Button key.

int KEYCODE_BUTTON_MODE
Key code constant: Mode Button key.

int KEYCODE_BUTTON_R1
Key code constant: R1 Button key.

int KEYCODE_BUTTON_R2
Key code constant: R2 Button key.

int KEYCODE_BUTTON_SELECT
Key code constant: Select Button key.

int KEYCODE_BUTTON_START
Key code constant: Start Button key.

int KEYCODE_BUTTON_THUMBL
Key code constant: Left Thumb Button key.

int KEYCODE_BUTTON_THUMBR
Key code constant: Right Thumb Button key.

int KEYCODE_BUTTON_X
Key code constant: X Button key.

int KEYCODE_BUTTON_Y
Key code constant: Y Button key.

int KEYCODE_BUTTON_Z
Key code constant: Z Button key.

int KEYCODE_C
Key code constant: 'C' key.

int KEYCODE_CALCULATOR
Key code constant: Calculator special function key.

int KEYCODE_CALENDAR
Key code constant: Calendar special function key.

int KEYCODE_CALL
Key code constant: Call key.

int KEYCODE_CAMERA
Key code constant: Camera key.

int KEYCODE_CAPS_LOCK
Key code constant: Caps Lock key.

int KEYCODE_CAPTIONS
Key code constant: Toggle captions key.

int KEYCODE_CHANNEL_DOWN
Key code constant: Channel down key.

int KEYCODE_CHANNEL_UP
Key code constant: Channel up key.

int KEYCODE_CLEAR
Key code constant: Clear key.

int KEYCODE_COMMA
Key code constant: ',' key.

int KEYCODE_CONTACTS
Key code constant: Contacts special function key.

int KEYCODE_COPY
Key code constant: Copy key.

int KEYCODE_CTRL_LEFT
Key code constant: Left Control modifier key.

int KEYCODE_CTRL_RIGHT
Key code constant: Right Control modifier key.

int KEYCODE_CUT
Key code constant: Cut key.

int KEYCODE_D
Key code constant: 'D' key.

int KEYCODE_DEL
Key code constant: Backspace key.

int KEYCODE_DPAD_CENTER
Key code constant: Directional Pad Center key.

int KEYCODE_DPAD_DOWN
Key code constant: Directional Pad Down key.

int KEYCODE_DPAD_DOWN_LEFT
Key code constant: Directional Pad Down-Left

int KEYCODE_DPAD_DOWN_RIGHT
Key code constant: Directional Pad Down-Right

int KEYCODE_DPAD_LEFT
Key code constant: Directional Pad Left key.

int KEYCODE_DPAD_RIGHT
Key code constant: Directional Pad Right key.

int KEYCODE_DPAD_UP
Key code constant: Directional Pad Up key.

int KEYCODE_DPAD_UP_LEFT
Key code constant: Directional Pad Up-Left

int KEYCODE_DPAD_UP_RIGHT
Key code constant: Directional Pad Up-Right

int KEYCODE_DVR
Key code constant: DVR key.

int KEYCODE_E
Key code constant: 'E' key.

int KEYCODE_EISU
Key code constant: Japanese alphanumeric key.

int KEYCODE_ENDCALL
Key code constant: End Call key.

int KEYCODE_ENTER
Key code constant: Enter key.

int KEYCODE_ENVELOPE
Key code constant: Envelope special function key.

int KEYCODE_EQUALS
Key code constant: '=' key.

int KEYCODE_ESCAPE
Key code constant: Escape key.

int KEYCODE_EXPLORER
Key code constant: Explorer special function key.

int KEYCODE_F
Key code constant: 'F' key.

int KEYCODE_F1
Key code constant: F1 key.

int KEYCODE_F10
Key code constant: F10 key.

int KEYCODE_F11
Key code constant: F11 key.

int KEYCODE_F12
Key code constant: F12 key.

int KEYCODE_F2
Key code constant: F2 key.

int KEYCODE_F3
Key code constant: F3 key.

int KEYCODE_F4
Key code constant: F4 key.

int KEYCODE_F5
Key code constant: F5 key.

int KEYCODE_F6
Key code constant: F6 key.

int KEYCODE_F7
Key code constant: F7 key.

int KEYCODE_F8
Key code constant: F8 key.

int KEYCODE_F9
Key code constant: F9 key.

int KEYCODE_FOCUS
Key code constant: Camera Focus key.

int KEYCODE_FORWARD
Key code constant: Forward key.

int KEYCODE_FORWARD_DEL
Key code constant: Forward Delete key.

int KEYCODE_FUNCTION
Key code constant: Function modifier key.

int KEYCODE_G
Key code constant: 'G' key.

int KEYCODE_GRAVE
Key code constant: '`' (backtick) key.

int KEYCODE_GUIDE
Key code constant: Guide key.

int KEYCODE_H
Key code constant: 'H' key.

int KEYCODE_HEADSETHOOK
Key code constant: Headset Hook key.

int KEYCODE_HELP
Key code constant: Help key.

int KEYCODE_HENKAN
Key code constant: Japanese conversion key.

int KEYCODE_HOME
Key code constant: Home key.

int KEYCODE_I
Key code constant: 'I' key.

int KEYCODE_INFO
Key code constant: Info key.

int KEYCODE_INSERT
Key code constant: Insert key.

int KEYCODE_J
Key code constant: 'J' key.

int KEYCODE_K
Key code constant: 'K' key.

int KEYCODE_KANA
Key code constant: Japanese kana key.

int KEYCODE_KATAKANA_HIRAGANA
Key code constant: Japanese katakana / hiragana key.

int KEYCODE_L
Key code constant: 'L' key.

int KEYCODE_LANGUAGE_SWITCH
Key code constant: Language Switch key.

int KEYCODE_LAST_CHANNEL
Key code constant: Last Channel key.

int KEYCODE_LEFT_BRACKET
Key code constant: '[' key.

int KEYCODE_M
Key code constant: 'M' key.

int KEYCODE_MANNER_MODE
Key code constant: Manner Mode key.

int KEYCODE_MEDIA_AUDIO_TRACK
Key code constant: Audio Track key.

int KEYCODE_MEDIA_CLOSE
Key code constant: Close media key.

int KEYCODE_MEDIA_EJECT
Key code constant: Eject media key.

int KEYCODE_MEDIA_FAST_FORWARD
Key code constant: Fast Forward media key.

int KEYCODE_MEDIA_NEXT
Key code constant: Play Next media key.

int KEYCODE_MEDIA_PAUSE
Key code constant: Pause media key.

int KEYCODE_MEDIA_PLAY
Key code constant: Play media key.

int KEYCODE_MEDIA_PLAY_PAUSE
Key code constant: Play/Pause media key.

int KEYCODE_MEDIA_PREVIOUS
Key code constant: Play Previous media key.

int KEYCODE_MEDIA_RECORD
Key code constant: Record media key.

int KEYCODE_MEDIA_REWIND
Key code constant: Rewind media key.

int KEYCODE_MEDIA_SKIP_BACKWARD
Key code constant: Skip backward media key.

int KEYCODE_MEDIA_SKIP_FORWARD
Key code constant: Skip forward media key.

int KEYCODE_MEDIA_STEP_BACKWARD
Key code constant: Step backward media key.

int KEYCODE_MEDIA_STEP_FORWARD
Key code constant: Step forward media key.

int KEYCODE_MEDIA_STOP
Key code constant: Stop media key.

int KEYCODE_MEDIA_TOP_MENU
Key code constant: Media Top Menu key.

int KEYCODE_MENU
Key code constant: Menu key.

int KEYCODE_META_LEFT
Key code constant: Left Meta modifier key.

int KEYCODE_META_RIGHT
Key code constant: Right Meta modifier key.

int KEYCODE_MINUS
Key code constant: '-'.

int KEYCODE_MOVE_END
Key code constant: End Movement key.

int KEYCODE_MOVE_HOME
Key code constant: Home Movement key.

int KEYCODE_MUHENKAN
Key code constant: Japanese non-conversion key.

int KEYCODE_MUSIC
Key code constant: Music special function key.

int KEYCODE_MUTE
Key code constant: Mute key.

int KEYCODE_N
Key code constant: 'N' key.

int KEYCODE_NAVIGATE_IN
Key code constant: Navigate in key.

int KEYCODE_NAVIGATE_NEXT
Key code constant: Navigate to next key.

int KEYCODE_NAVIGATE_OUT
Key code constant: Navigate out key.

int KEYCODE_NAVIGATE_PREVIOUS
Key code constant: Navigate to previous key.

int KEYCODE_NOTIFICATION
Key code constant: Notification key.

int KEYCODE_NUM
Key code constant: Number modifier key.

int KEYCODE_NUMPAD_0
Key code constant: Numeric keypad '0' key.

int KEYCODE_NUMPAD_1
Key code constant: Numeric keypad '1' key.

int KEYCODE_NUMPAD_2
Key code constant: Numeric keypad '2' key.

int KEYCODE_NUMPAD_3
Key code constant: Numeric keypad '3' key.

int KEYCODE_NUMPAD_4
Key code constant: Numeric keypad '4' key.

int KEYCODE_NUMPAD_5
Key code constant: Numeric keypad '5' key.

int KEYCODE_NUMPAD_6
Key code constant: Numeric keypad '6' key.

int KEYCODE_NUMPAD_7
Key code constant: Numeric keypad '7' key.

int KEYCODE_NUMPAD_8
Key code constant: Numeric keypad '8' key.

int KEYCODE_NUMPAD_9
Key code constant: Numeric keypad '9' key.

int KEYCODE_NUMPAD_ADD
Key code constant: Numeric keypad '+' key (for addition).

int KEYCODE_NUMPAD_COMMA
Key code constant: Numeric keypad ',' key (for decimals or digit grouping).

int KEYCODE_NUMPAD_DIVIDE
Key code constant: Numeric keypad '/' key (for division).

int KEYCODE_NUMPAD_DOT
Key code constant: Numeric keypad '.' key (for decimals or digit grouping).

int KEYCODE_NUMPAD_ENTER
Key code constant: Numeric keypad Enter key.

int KEYCODE_NUMPAD_EQUALS
Key code constant: Numeric keypad '=' key.

int KEYCODE_NUMPAD_LEFT_PAREN
Key code constant: Numeric keypad '(' key.

int KEYCODE_NUMPAD_MULTIPLY
Key code constant: Numeric keypad '*' key (for multiplication).

int KEYCODE_NUMPAD_RIGHT_PAREN
Key code constant: Numeric keypad ')' key.

int KEYCODE_NUMPAD_SUBTRACT
Key code constant: Numeric keypad '-' key (for subtraction).

int KEYCODE_NUM_LOCK
Key code constant: Num Lock key.

int KEYCODE_O
Key code constant: 'O' key.

int KEYCODE_P
Key code constant: 'P' key.

int KEYCODE_PAGE_DOWN
Key code constant: Page Down key.

int KEYCODE_PAGE_UP
Key code constant: Page Up key.

int KEYCODE_PAIRING
Key code constant: Pairing key.

int KEYCODE_PASTE
Key code constant: Paste key.

int KEYCODE_PERIOD
Key code constant: '.' key.

int KEYCODE_PICTSYMBOLS
Key code constant: Picture Symbols modifier key.

int KEYCODE_PLUS
Key code constant: '+' key.

int KEYCODE_POUND
Key code constant: '#' key.

int KEYCODE_POWER
Key code constant: Power key.

int KEYCODE_PROFILE_SWITCH
Key code constant: Used to switch current Account that is consuming content.

int KEYCODE_PROG_BLUE
Key code constant: Blue "programmable" key.

int KEYCODE_PROG_GREEN
Key code constant: Green "programmable" key.

int KEYCODE_PROG_RED
Key code constant: Red "programmable" key.

int KEYCODE_PROG_YELLOW
Key code constant: Yellow "programmable" key.

int KEYCODE_Q
Key code constant: 'Q' key.

int KEYCODE_R
Key code constant: 'R' key.

int KEYCODE_REFRESH
Key code constant: Refresh key.

int KEYCODE_RIGHT_BRACKET
Key code constant: ']' key.

int KEYCODE_RO
Key code constant: Japanese Ro key.

int KEYCODE_S
Key code constant: 'S' key.

int KEYCODE_SCROLL_LOCK
Key code constant: Scroll Lock key.

int KEYCODE_SEARCH
Key code constant: Search key.

int KEYCODE_SEMICOLON
Key code constant: ';' key.

int KEYCODE_SETTINGS
Key code constant: Settings key.

int KEYCODE_SHIFT_LEFT
Key code constant: Left Shift modifier key.

int KEYCODE_SHIFT_RIGHT
Key code constant: Right Shift modifier key.

int KEYCODE_SLASH
Key code constant: '/' key.

int KEYCODE_SLEEP
Key code constant: Sleep key.

int KEYCODE_SOFT_LEFT
Key code constant: Soft Left key.

int KEYCODE_SOFT_RIGHT
Key code constant: Soft Right key.

int KEYCODE_SOFT_SLEEP
Key code constant: put device to sleep unless a wakelock is held.

int KEYCODE_SPACE
Key code constant: Space key.

int KEYCODE_STAR
Key code constant: '*' key.

int KEYCODE_STB_INPUT
Key code constant: Set-top-box input key.

int KEYCODE_STB_POWER
Key code constant: Set-top-box power key.

int KEYCODE_STEM_1
Key code constant: Generic stem key 1 for Wear

int KEYCODE_STEM_2
Key code constant: Generic stem key 2 for Wear

int KEYCODE_STEM_3
Key code constant: Generic stem key 3 for Wear

int KEYCODE_STEM_PRIMARY
Key code constant: Primary stem key for Wear Main power/reset button on watch.

int KEYCODE_SWITCH_CHARSET
Key code constant: Switch Charset modifier key.

int KEYCODE_SYM
Key code constant: Symbol modifier key.

int KEYCODE_SYSRQ
Key code constant: System Request / Print Screen key.

int KEYCODE_SYSTEM_NAVIGATION_DOWN
Key code constant: Consumed by the system for navigation down

int KEYCODE_SYSTEM_NAVIGATION_LEFT
Key code constant: Consumed by the system for navigation left

int KEYCODE_SYSTEM_NAVIGATION_RIGHT
Key code constant: Consumed by the system for navigation right

int KEYCODE_SYSTEM_NAVIGATION_UP
Key code constant: Consumed by the system for navigation up

int KEYCODE_T
Key code constant: 'T' key.

int KEYCODE_TAB
Key code constant: Tab key.

int KEYCODE_THUMBS_DOWN
Key code constant: Thumbs down key.

int KEYCODE_THUMBS_UP
Key code constant: Thumbs up key.

int KEYCODE_TV
Key code constant: TV key.

int KEYCODE_TV_ANTENNA_CABLE
Key code constant: Antenna/Cable key.

int KEYCODE_TV_AUDIO_DESCRIPTION
Key code constant: Audio description key.

int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN
Key code constant: Audio description mixing volume down key.

int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP
Key code constant: Audio description mixing volume up key.

int KEYCODE_TV_CONTENTS_MENU
Key code constant: Contents menu key.

int KEYCODE_TV_DATA_SERVICE
Key code constant: TV data service key.

int KEYCODE_TV_INPUT
Key code constant: TV input key.

int KEYCODE_TV_INPUT_COMPONENT_1
Key code constant: Component #1 key.

int KEYCODE_TV_INPUT_COMPONENT_2
Key code constant: Component #2 key.

int KEYCODE_TV_INPUT_COMPOSITE_1
Key code constant: Composite #1 key.

int KEYCODE_TV_INPUT_COMPOSITE_2
Key code constant: Composite #2 key.

int KEYCODE_TV_INPUT_HDMI_1
Key code constant: HDMI #1 key.

int KEYCODE_TV_INPUT_HDMI_2
Key code constant: HDMI #2 key.

int KEYCODE_TV_INPUT_HDMI_3
Key code constant: HDMI #3 key.

int KEYCODE_TV_INPUT_HDMI_4
Key code constant: HDMI #4 key.

int KEYCODE_TV_INPUT_VGA_1
Key code constant: VGA #1 key.

int KEYCODE_TV_MEDIA_CONTEXT_MENU
Key code constant: Media context menu key.

int KEYCODE_TV_NETWORK
Key code constant: Toggle Network key.

int KEYCODE_TV_NUMBER_ENTRY
Key code constant: Number entry key.

int KEYCODE_TV_POWER
Key code constant: TV power key.

int KEYCODE_TV_RADIO_SERVICE
Key code constant: Radio key.

int KEYCODE_TV_SATELLITE
Key code constant: Satellite key.

int KEYCODE_TV_SATELLITE_BS
Key code constant: BS key.

int KEYCODE_TV_SATELLITE_CS
Key code constant: CS key.

int KEYCODE_TV_SATELLITE_SERVICE
Key code constant: BS/CS key.

int KEYCODE_TV_TELETEXT
Key code constant: Teletext key.

int KEYCODE_TV_TERRESTRIAL_ANALOG
Key code constant: Analog Terrestrial key.

int KEYCODE_TV_TERRESTRIAL_DIGITAL
Key code constant: Digital Terrestrial key.

int KEYCODE_TV_TIMER_PROGRAMMING
Key code constant: Timer programming key.

int KEYCODE_TV_ZOOM_MODE
Key code constant: Zoom mode key.

int KEYCODE_U
Key code constant: 'U' key.

int KEYCODE_UNKNOWN
Key code constant: Unknown key code.

int KEYCODE_V
Key code constant: 'V' key.

int KEYCODE_VOICE_ASSIST
Key code constant: Voice Assist key.

int KEYCODE_VOLUME_DOWN
Key code constant: Volume Down key.

int KEYCODE_VOLUME_MUTE
Key code constant: Volume Mute key.

int KEYCODE_VOLUME_UP
Key code constant: Volume Up key.

int KEYCODE_W
Key code constant: 'W' key.

int KEYCODE_WAKEUP
Key code constant: Wakeup key.

int KEYCODE_WINDOW
Key code constant: Window key.

int KEYCODE_X
Key code constant: 'X' key.

int KEYCODE_Y
Key code constant: 'Y' key.

int KEYCODE_YEN
Key code constant: Japanese Yen key.

int KEYCODE_Z
Key code constant: 'Z' key.

int KEYCODE_ZENKAKU_HANKAKU
Key code constant: Japanese full-width / half-width key.

int KEYCODE_ZOOM_IN
Key code constant: Zoom in key.

int KEYCODE_ZOOM_OUT
Key code constant: Zoom out key.

int MAX_KEYCODE
This constant was deprecated in API level 15. There are now more than MAX_KEYCODE keycodes. Use getMaxKeyCode() instead.

int META_ALT_LEFT_ON
This mask is used to check whether the left ALT meta key is pressed.

int META_ALT_MASK
This mask is a combination of META_ALT_ON, META_ALT_LEFT_ON and META_ALT_RIGHT_ON.

int META_ALT_ON
This mask is used to check whether one of the ALT meta keys is pressed.

int META_ALT_RIGHT_ON
This mask is used to check whether the right the ALT meta key is pressed.

int META_CAPS_LOCK_ON
This mask is used to check whether the CAPS LOCK meta key is on.

int META_CTRL_LEFT_ON
This mask is used to check whether the left CTRL meta key is pressed.

int META_CTRL_MASK
This mask is a combination of META_CTRL_ON, META_CTRL_LEFT_ON and META_CTRL_RIGHT_ON.

int META_CTRL_ON
This mask is used to check whether one of the CTRL meta keys is pressed.

int META_CTRL_RIGHT_ON
This mask is used to check whether the right CTRL meta key is pressed.

int META_FUNCTION_ON
This mask is used to check whether the FUNCTION meta key is pressed.

int META_META_LEFT_ON
This mask is used to check whether the left META meta key is pressed.

int META_META_MASK
This mask is a combination of META_META_ON, META_META_LEFT_ON and META_META_RIGHT_ON.

int META_META_ON
This mask is used to check whether one of the META meta keys is pressed.

int META_META_RIGHT_ON
This mask is used to check whether the right META meta key is pressed.

int META_NUM_LOCK_ON
This mask is used to check whether the NUM LOCK meta key is on.

int META_SCROLL_LOCK_ON
This mask is used to check whether the SCROLL LOCK meta key is on.

int META_SHIFT_LEFT_ON
This mask is used to check whether the left SHIFT meta key is pressed.

int META_SHIFT_MASK
This mask is a combination of META_SHIFT_ON, META_SHIFT_LEFT_ON and META_SHIFT_RIGHT_ON.

int META_SHIFT_ON
This mask is used to check whether one of the SHIFT meta keys is pressed.

int META_SHIFT_RIGHT_ON
This mask is used to check whether the right SHIFT meta key is pressed.

int META_SYM_ON
This mask is used to check whether the SYM meta key is pressed.

Inherited constants
From interface android.os.Parcelable
Fields
public static final Creator CREATOR
Inherited fields
From class android.view.InputEvent
Public constructors
KeyEvent(int action, int code)
Create a new key event.

KeyEvent(long downTime, long eventTime, int action, int code, int repeat)
Create a new key event.

KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState)
Create a new key event.

KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode)
Create a new key event.

KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode, int flags)
Create a new key event.

KeyEvent(long downTime, long eventTime, int action, int code, int repeat, int metaState, int deviceId, int scancode, int flags, int source)
Create a new key event.

KeyEvent(long time, String characters, int deviceId, int flags)
Create a new key event for a string of characters.

KeyEvent(KeyEvent origEvent)
Make an exact copy of an existing key event.

KeyEvent(KeyEvent origEvent, long eventTime, int newRepeat)
This constructor is deprecated. Use changeTimeRepeat(android.view.KeyEvent, long, int) instead.

Public methods
static KeyEvent changeAction(KeyEvent event, int action)
Create a new key event that is the same as the given one, but whose action is replaced with the given value.

static KeyEvent changeFlags(KeyEvent event, int flags)
Create a new key event that is the same as the given one, but whose flags are replaced with the given value.

static KeyEvent changeTimeRepeat(KeyEvent event, long eventTime, int newRepeat, int newFlags)
Create a new key event that is the same as the given one, but whose event time and repeat count are replaced with the given value.

static KeyEvent changeTimeRepeat(KeyEvent event, long eventTime, int newRepeat)
Create a new key event that is the same as the given one, but whose event time and repeat count are replaced with the given value.

final boolean dispatch(KeyEvent.Callback receiver, KeyEvent.DispatcherState state, Object target)
Deliver this key event to a Callback interface.

final boolean dispatch(KeyEvent.Callback receiver)
This method was deprecated in API level 15. Use dispatch(android.view.KeyEvent.Callback, android.view.KeyEvent.DispatcherState, java.lang.Object) instead.

final int getAction()
Retrieve the action of this key event.

final String getCharacters()
This method was deprecated in API level 29. no longer used by the input system.

static int getDeadChar(int accent, int c)
Get the character that is produced by putting accent on the character c.

final int getDeviceId()
Gets the id for the device that this event came from.

char getDisplayLabel()
Gets the primary character for this key.

final long getDownTime()
Retrieve the time of the most recent key down event, in the SystemClock.uptimeMillis() time base.

final long getEventTime()
Retrieve the time this event occurred, in the SystemClock.uptimeMillis() time base.

final int getFlags()
Returns the flags for this key event.

final KeyCharacterMap getKeyCharacterMap()
Gets the KeyCharacterMap associated with the keyboard device.

final int getKeyCode()
Retrieve the key code of the key event.

boolean getKeyData(KeyCharacterMap.KeyData results)
This method was deprecated in API level 15. instead use getDisplayLabel(), getNumber() or getUnicodeChar(int).

char getMatch(char[] chars, int metaState)
Gets the first character in the character array that can be generated by the specified key code.

char getMatch(char[] chars)
Gets the first character in the character array that can be generated by the specified key code.

static int getMaxKeyCode()
Returns the maximum keycode.

final int getMetaState()
Returns the state of the meta keys.

static int getModifierMetaStateMask()
Gets a mask that includes all valid modifier key meta state bits.

final int getModifiers()
Returns the state of the modifier keys.

char getNumber()
Gets the number or symbol associated with the key.

final int getRepeatCount()
Retrieve the repeat count of the event.

final int getScanCode()
Retrieve the hardware key id of this key event. These values are not reliable and vary from device to device.

final int getSource()
Gets the source of the event.

int getUnicodeChar(int metaState)
Gets the Unicode character generated by the specified key and meta key state combination.

int getUnicodeChar()
Gets the Unicode character generated by the specified key and meta key state combination.

final boolean hasModifiers(int modifiers)
Returns true if only the specified modifiers keys are pressed.

final boolean hasNoModifiers()
Returns true if no modifier keys are pressed.

final boolean isAltPressed()
Returns the pressed state of the ALT meta key.

final boolean isCanceled()
For ACTION_UP events, indicates that the event has been canceled as per FLAG_CANCELED.

final boolean isCapsLockOn()
Returns the locked state of the CAPS LOCK meta key.

final boolean isCtrlPressed()
Returns the pressed state of the CTRL meta key.

final boolean isFunctionPressed()
Returns the pressed state of the FUNCTION meta key.

static final boolean isGamepadButton(int keyCode)
Returns true if the specified keycode is a gamepad button.

final boolean isLongPress()
For ACTION_DOWN events, indicates that the event has been canceled as per FLAG_LONG_PRESS.

final boolean isMetaPressed()
Returns the pressed state of the META meta key.

static boolean isModifierKey(int keyCode)
Returns true if this key code is a modifier key.

final boolean isNumLockOn()
Returns the locked state of the NUM LOCK meta key.

boolean isPrintingKey()
Returns true if this key produces a glyph.

final boolean isScrollLockOn()
Returns the locked state of the SCROLL LOCK meta key.

final boolean isShiftPressed()
Returns the pressed state of the SHIFT meta key.

final boolean isSymPressed()
Returns the pressed state of the SYM meta key.

final boolean isSystem()
Is this a system key? System keys can not be used for menu shortcuts.

final boolean isTracking()
For ACTION_UP events, indicates that the event is still being tracked from its initial down event as per FLAG_TRACKING.

static int keyCodeFromString(String symbolicName)
Gets a keycode by its symbolic name such as "KEYCODE_A" or an equivalent numeric constant such as "29".

static String keyCodeToString(int keyCode)
Returns a string that represents the symbolic name of the specified keycode such as "KEYCODE_A", "KEYCODE_DPAD_UP", or an equivalent numeric constant such as "1001" if unknown.

static boolean metaStateHasModifiers(int metaState, int modifiers)
Returns true if only the specified modifier keys are pressed according to the specified meta state.

static boolean metaStateHasNoModifiers(int metaState)
Returns true if no modifiers keys are pressed according to the specified meta state.

static int normalizeMetaState(int metaState)
Normalizes the specified meta state.

final void setSource(int source)
final void startTracking()
Call this during Callback#onKeyDown to have the system track the key through its final up (possibly including a long press).

String toString()
Returns a string representation of the object.

void writeToParcel(Parcel out, int flags)
Flatten this object in to a Parcel.

Inherited methods
From class android.view.InputEvent
From class java.lang.Object
From interface android.os.Parcelable
Constants
ACTION_DOWN
Added in API level 1
public static final int ACTION_DOWN
getAction() value: the key has been pressed down.

Constant Value: 0 (0x00000000)

ACTION_MULTIPLE
Added in API level 1
Deprecated in API level 29
public static final int ACTION_MULTIPLE
This constant was deprecated in API level 29.
No longer used by the input system. getAction() value: multiple duplicate key events have occurred in a row, or a complex string is being delivered. If the key code is not KEYCODE_UNKNOWN then the getRepeatCount() method returns the number of times the given key code should be executed. Otherwise, if the key code is KEYCODE_UNKNOWN, then this is a sequence of characters as returned by getCharacters().

Constant Value: 2 (0x00000002)

ACTION_UP
Added in API level 1
public static final int ACTION_UP
getAction() value: the key has been released.

Constant Value: 1 (0x00000001)

FLAG_CANCELED
Added in API level 5
public static final int FLAG_CANCELED
When associated with up key events, this indicates that the key press has been canceled. Typically this is used with virtual touch screen keys, where the user can slide from the virtual key area on to the display: in that case, the application will receive a canceled up event and should not perform the action normally associated with the key. Note that for this to work, the application can not perform an action for a key until it receives an up or the long press timeout has expired.

Constant Value: 32 (0x00000020)

FLAG_CANCELED_LONG_PRESS
Added in API level 5
public static final int FLAG_CANCELED_LONG_PRESS
Set when a key event has FLAG_CANCELED set because a long press action was executed while it was down.

Constant Value: 256 (0x00000100)

FLAG_EDITOR_ACTION
Added in API level 3
public static final int FLAG_EDITOR_ACTION
This mask is used for compatibility, to identify enter keys that are coming from an IME whose enter key has been auto-labelled "next" or "done". This allows TextView to dispatch these as normal enter keys for old applications, but still do the appropriate action when receiving them.

Constant Value: 16 (0x00000010)

FLAG_FALLBACK
Added in API level 11
public static final int FLAG_FALLBACK
Set when a key event has been synthesized to implement default behavior for an event that the application did not handle. Fallback key events are generated by unhandled trackball motions (to emulate a directional keypad) and by certain unhandled key presses that are declared in the key map (such as special function numeric keypad keys when numlock is off).

Constant Value: 1024 (0x00000400)

FLAG_FROM_SYSTEM
Added in API level 3
public static final int FLAG_FROM_SYSTEM
This mask is set if an event was known to come from a trusted part of the system. That is, the event is known to come from the user, and could not have been spoofed by a third party component.

Constant Value: 8 (0x00000008)

FLAG_KEEP_TOUCH_MODE
Added in API level 3
public static final int FLAG_KEEP_TOUCH_MODE
This mask is set if we don't want the key event to cause us to leave touch mode.

Constant Value: 4 (0x00000004)

FLAG_LONG_PRESS
Added in API level 5
public static final int FLAG_LONG_PRESS
This flag is set for the first key repeat that occurs after the long press timeout.

Constant Value: 128 (0x00000080)

FLAG_SOFT_KEYBOARD
Added in API level 3
public static final int FLAG_SOFT_KEYBOARD
This mask is set if the key event was generated by a software keyboard.

Constant Value: 2 (0x00000002)

FLAG_TRACKING
Added in API level 5
public static final int FLAG_TRACKING
Set for ACTION_UP when this event's key code is still being tracked from its initial down. That is, somebody requested that tracking started on the key down and a long press has not caused the tracking to be canceled.

Constant Value: 512 (0x00000200)

FLAG_VIRTUAL_HARD_KEY
Added in API level 5
public static final int FLAG_VIRTUAL_HARD_KEY
This key event was generated by a virtual (on-screen) hard key area. Typically this is an area of the touchscreen, outside of the regular display, dedicated to "hardware" buttons.

Constant Value: 64 (0x00000040)

FLAG_WOKE_HERE
Added in API level 1
Deprecated in API level 20
public static final int FLAG_WOKE_HERE
This constant was deprecated in API level 20.
This flag will never be set by the system since the system consumes all wake keys itself.

This mask is set if the device woke because of this key event.

Constant Value: 1 (0x00000001)

KEYCODE_0
Added in API level 1
public static final int KEYCODE_0
Key code constant: '0' key.

Constant Value: 7 (0x00000007)

KEYCODE_1
Added in API level 1
public static final int KEYCODE_1
Key code constant: '1' key.

Constant Value: 8 (0x00000008)

KEYCODE_11
Added in API level 21
public static final int KEYCODE_11
Key code constant: '11' key.

Constant Value: 227 (0x000000e3)

KEYCODE_12
Added in API level 21
public static final int KEYCODE_12
Key code constant: '12' key.

Constant Value: 228 (0x000000e4)

KEYCODE_2
Added in API level 1
public static final int KEYCODE_2
Key code constant: '2' key.

Constant Value: 9 (0x00000009)

KEYCODE_3
Added in API level 1
public static final int KEYCODE_3
Key code constant: '3' key.

Constant Value: 10 (0x0000000a)

KEYCODE_3D_MODE
public static final int KEYCODE_3D_MODE
Key code constant: 3D Mode key. Toggles the display between 2D and 3D mode. * @apiSince 14

Constant Value: 206 (0x000000ce)

KEYCODE_4
Added in API level 1
public static final int KEYCODE_4
Key code constant: '4' key.

Constant Value: 11 (0x0000000b)

KEYCODE_5
Added in API level 1
public static final int KEYCODE_5
Key code constant: '5' key.

Constant Value: 12 (0x0000000c)

KEYCODE_6
Added in API level 1
public static final int KEYCODE_6
Key code constant: '6' key.

Constant Value: 13 (0x0000000d)

KEYCODE_7
Added in API level 1
public static final int KEYCODE_7
Key code constant: '7' key.

Constant Value: 14 (0x0000000e)

KEYCODE_8
Added in API level 1
public static final int KEYCODE_8
Key code constant: '8' key.

Constant Value: 15 (0x0000000f)

KEYCODE_9
Added in API level 1
public static final int KEYCODE_9
Key code constant: '9' key.

Constant Value: 16 (0x00000010)

KEYCODE_A
Added in API level 1
public static final int KEYCODE_A
Key code constant: 'A' key.

Constant Value: 29 (0x0000001d)

KEYCODE_ALL_APPS
Added in API level 28
public static final int KEYCODE_ALL_APPS
Key code constant: Show all apps

Constant Value: 284 (0x0000011c)

KEYCODE_ALT_LEFT
Added in API level 1
public static final int KEYCODE_ALT_LEFT
Key code constant: Left Alt modifier key.

Constant Value: 57 (0x00000039)

KEYCODE_ALT_RIGHT
Added in API level 1
public static final int KEYCODE_ALT_RIGHT
Key code constant: Right Alt modifier key.

Constant Value: 58 (0x0000003a)

KEYCODE_APOSTROPHE
Added in API level 1
public static final int KEYCODE_APOSTROPHE
Key code constant: ''' (apostrophe) key.

Constant Value: 75 (0x0000004b)

KEYCODE_APP_SWITCH
public static final int KEYCODE_APP_SWITCH
Key code constant: App switch key. Should bring up the application switcher dialog. * @apiSince 11

Constant Value: 187 (0x000000bb)

KEYCODE_ASSIST
public static final int KEYCODE_ASSIST
Key code constant: Assist key. Launches the global assist activity. Not delivered to applications. * @apiSince 16

Constant Value: 219 (0x000000db)

KEYCODE_AT
Added in API level 1
public static final int KEYCODE_AT
Key code constant: '@' key.

Constant Value: 77 (0x0000004d)

KEYCODE_AVR_INPUT
public static final int KEYCODE_AVR_INPUT
Key code constant: A/V Receiver input key. On TV remotes, switches the input mode on an external A/V Receiver. * @apiSince 11

Constant Value: 182 (0x000000b6)

KEYCODE_AVR_POWER
public static final int KEYCODE_AVR_POWER
Key code constant: A/V Receiver power key. On TV remotes, toggles the power on an external A/V Receiver. * @apiSince 11

Constant Value: 181 (0x000000b5)

KEYCODE_B
Added in API level 1
public static final int KEYCODE_B
Key code constant: 'B' key.

Constant Value: 30 (0x0000001e)

KEYCODE_BACK
Added in API level 1
public static final int KEYCODE_BACK
Key code constant: Back key.

Constant Value: 4 (0x00000004)

KEYCODE_BACKSLASH
Added in API level 1
public static final int KEYCODE_BACKSLASH
Key code constant: '\' key.

Constant Value: 73 (0x00000049)

KEYCODE_BOOKMARK
public static final int KEYCODE_BOOKMARK
Key code constant: Bookmark key. On some TV remotes, bookmarks content or web pages. * @apiSince 11

Constant Value: 174 (0x000000ae)

KEYCODE_BREAK
Added in API level 11
public static final int KEYCODE_BREAK
Key code constant: Break / Pause key.

Constant Value: 121 (0x00000079)

KEYCODE_BRIGHTNESS_DOWN
public static final int KEYCODE_BRIGHTNESS_DOWN
Key code constant: Brightness Down key. Adjusts the screen brightness down. * @apiSince 18

Constant Value: 220 (0x000000dc)

KEYCODE_BRIGHTNESS_UP
public static final int KEYCODE_BRIGHTNESS_UP
Key code constant: Brightness Up key. Adjusts the screen brightness up. * @apiSince 18

Constant Value: 221 (0x000000dd)

KEYCODE_BUTTON_1
Added in API level 12
public static final int KEYCODE_BUTTON_1
Key code constant: Generic Game Pad Button #1.

Constant Value: 188 (0x000000bc)

KEYCODE_BUTTON_10
Added in API level 12
public static final int KEYCODE_BUTTON_10
Key code constant: Generic Game Pad Button #10.

Constant Value: 197 (0x000000c5)

KEYCODE_BUTTON_11
Added in API level 12
public static final int KEYCODE_BUTTON_11
Key code constant: Generic Game Pad Button #11.

Constant Value: 198 (0x000000c6)

KEYCODE_BUTTON_12
Added in API level 12
public static final int KEYCODE_BUTTON_12
Key code constant: Generic Game Pad Button #12.

Constant Value: 199 (0x000000c7)

KEYCODE_BUTTON_13
Added in API level 12
public static final int KEYCODE_BUTTON_13
Key code constant: Generic Game Pad Button #13.

Constant Value: 200 (0x000000c8)

KEYCODE_BUTTON_14
Added in API level 12
public static final int KEYCODE_BUTTON_14
Key code constant: Generic Game Pad Button #14.

Constant Value: 201 (0x000000c9)

KEYCODE_BUTTON_15
Added in API level 12
public static final int KEYCODE_BUTTON_15
Key code constant: Generic Game Pad Button #15.

Constant Value: 202 (0x000000ca)

KEYCODE_BUTTON_16
Added in API level 12
public static final int KEYCODE_BUTTON_16
Key code constant: Generic Game Pad Button #16.

Constant Value: 203 (0x000000cb)

KEYCODE_BUTTON_2
Added in API level 12
public static final int KEYCODE_BUTTON_2
Key code constant: Generic Game Pad Button #2.

Constant Value: 189 (0x000000bd)

KEYCODE_BUTTON_3
Added in API level 12
public static final int KEYCODE_BUTTON_3
Key code constant: Generic Game Pad Button #3.

Constant Value: 190 (0x000000be)

KEYCODE_BUTTON_4
Added in API level 12
public static final int KEYCODE_BUTTON_4
Key code constant: Generic Game Pad Button #4.

Constant Value: 191 (0x000000bf)

KEYCODE_BUTTON_5
Added in API level 12
public static final int KEYCODE_BUTTON_5
Key code constant: Generic Game Pad Button #5.

Constant Value: 192 (0x000000c0)

KEYCODE_BUTTON_6
Added in API level 12
public static final int KEYCODE_BUTTON_6
Key code constant: Generic Game Pad Button #6.

Constant Value: 193 (0x000000c1)

KEYCODE_BUTTON_7
Added in API level 12
public static final int KEYCODE_BUTTON_7
Key code constant: Generic Game Pad Button #7.

Constant Value: 194 (0x000000c2)

KEYCODE_BUTTON_8
Added in API level 12
public static final int KEYCODE_BUTTON_8
Key code constant: Generic Game Pad Button #8.

Constant Value: 195 (0x000000c3)

KEYCODE_BUTTON_9
Added in API level 12
public static final int KEYCODE_BUTTON_9
Key code constant: Generic Game Pad Button #9.

Constant Value: 196 (0x000000c4)

KEYCODE_BUTTON_A
public static final int KEYCODE_BUTTON_A
Key code constant: A Button key. On a game controller, the A button should be either the button labeled A or the first button on the bottom row of controller buttons. * @apiSince 9

Constant Value: 96 (0x00000060)

KEYCODE_BUTTON_B
public static final int KEYCODE_BUTTON_B
Key code constant: B Button key. On a game controller, the B button should be either the button labeled B or the second button on the bottom row of controller buttons. * @apiSince 9

Constant Value: 97 (0x00000061)

KEYCODE_BUTTON_C
public static final int KEYCODE_BUTTON_C
Key code constant: C Button key. On a game controller, the C button should be either the button labeled C or the third button on the bottom row of controller buttons. * @apiSince 9

Constant Value: 98 (0x00000062)

KEYCODE_BUTTON_L1
public static final int KEYCODE_BUTTON_L1
Key code constant: L1 Button key. On a game controller, the L1 button should be either the button labeled L1 (or L) or the top left trigger button. * @apiSince 9

Constant Value: 102 (0x00000066)

KEYCODE_BUTTON_L2
public static final int KEYCODE_BUTTON_L2
Key code constant: L2 Button key. On a game controller, the L2 button should be either the button labeled L2 or the bottom left trigger button. * @apiSince 9

Constant Value: 104 (0x00000068)

KEYCODE_BUTTON_MODE
public static final int KEYCODE_BUTTON_MODE
Key code constant: Mode Button key. On a game controller, the button labeled Mode. * @apiSince 9

Constant Value: 110 (0x0000006e)

KEYCODE_BUTTON_R1
public static final int KEYCODE_BUTTON_R1
Key code constant: R1 Button key. On a game controller, the R1 button should be either the button labeled R1 (or R) or the top right trigger button. * @apiSince 9

Constant Value: 103 (0x00000067)

KEYCODE_BUTTON_R2
public static final int KEYCODE_BUTTON_R2
Key code constant: R2 Button key. On a game controller, the R2 button should be either the button labeled R2 or the bottom right trigger button. * @apiSince 9

Constant Value: 105 (0x00000069)

KEYCODE_BUTTON_SELECT
public static final int KEYCODE_BUTTON_SELECT
Key code constant: Select Button key. On a game controller, the button labeled Select. * @apiSince 9

Constant Value: 109 (0x0000006d)

KEYCODE_BUTTON_START
public static final int KEYCODE_BUTTON_START
Key code constant: Start Button key. On a game controller, the button labeled Start. * @apiSince 9

Constant Value: 108 (0x0000006c)

KEYCODE_BUTTON_THUMBL
public static final int KEYCODE_BUTTON_THUMBL
Key code constant: Left Thumb Button key. On a game controller, the left thumb button indicates that the left (or only) joystick is pressed. * @apiSince 9

Constant Value: 106 (0x0000006a)

KEYCODE_BUTTON_THUMBR
public static final int KEYCODE_BUTTON_THUMBR
Key code constant: Right Thumb Button key. On a game controller, the right thumb button indicates that the right joystick is pressed. * @apiSince 9

Constant Value: 107 (0x0000006b)

KEYCODE_BUTTON_X
public static final int KEYCODE_BUTTON_X
Key code constant: X Button key. On a game controller, the X button should be either the button labeled X or the first button on the upper row of controller buttons. * @apiSince 9

Constant Value: 99 (0x00000063)

KEYCODE_BUTTON_Y
public static final int KEYCODE_BUTTON_Y
Key code constant: Y Button key. On a game controller, the Y button should be either the button labeled Y or the second button on the upper row of controller buttons. * @apiSince 9

Constant Value: 100 (0x00000064)

KEYCODE_BUTTON_Z
public static final int KEYCODE_BUTTON_Z
Key code constant: Z Button key. On a game controller, the Z button should be either the button labeled Z or the third button on the upper row of controller buttons. * @apiSince 9

Constant Value: 101 (0x00000065)

KEYCODE_C
Added in API level 1
public static final int KEYCODE_C
Key code constant: 'C' key.

Constant Value: 31 (0x0000001f)

KEYCODE_CALCULATOR
public static final int KEYCODE_CALCULATOR
Key code constant: Calculator special function key. Used to launch a calculator application. * @apiSince 15

Constant Value: 210 (0x000000d2)

KEYCODE_CALENDAR
public static final int KEYCODE_CALENDAR
Key code constant: Calendar special function key. Used to launch a calendar application. * @apiSince 15

Constant Value: 208 (0x000000d0)

KEYCODE_CALL
Added in API level 1
public static final int KEYCODE_CALL
Key code constant: Call key.

Constant Value: 5 (0x00000005)

KEYCODE_CAMERA
public static final int KEYCODE_CAMERA
Key code constant: Camera key. Used to launch a camera application or take pictures. * @apiSince 1

Constant Value: 27 (0x0000001b)

KEYCODE_CAPS_LOCK
Added in API level 11
public static final int KEYCODE_CAPS_LOCK
Key code constant: Caps Lock key.

Constant Value: 115 (0x00000073)

KEYCODE_CAPTIONS
public static final int KEYCODE_CAPTIONS
Key code constant: Toggle captions key. Switches the mode for closed-captioning text, for example during television shows. * @apiSince 11

Constant Value: 175 (0x000000af)

KEYCODE_CHANNEL_DOWN
public static final int KEYCODE_CHANNEL_DOWN
Key code constant: Channel down key. On TV remotes, decrements the television channel. * @apiSince 11

Constant Value: 167 (0x000000a7)

KEYCODE_CHANNEL_UP
public static final int KEYCODE_CHANNEL_UP
Key code constant: Channel up key. On TV remotes, increments the television channel. * @apiSince 11

Constant Value: 166 (0x000000a6)

KEYCODE_CLEAR
Added in API level 1
public static final int KEYCODE_CLEAR
Key code constant: Clear key.

Constant Value: 28 (0x0000001c)

KEYCODE_COMMA
Added in API level 1
public static final int KEYCODE_COMMA
Key code constant: ',' key.

Constant Value: 55 (0x00000037)

KEYCODE_CONTACTS
public static final int KEYCODE_CONTACTS
Key code constant: Contacts special function key. Used to launch an address book application. * @apiSince 15

Constant Value: 207 (0x000000cf)

KEYCODE_COPY
Added in API level 24
public static final int KEYCODE_COPY
Key code constant: Copy key.

Constant Value: 278 (0x00000116)

KEYCODE_CTRL_LEFT
Added in API level 11
public static final int KEYCODE_CTRL_LEFT
Key code constant: Left Control modifier key.

Constant Value: 113 (0x00000071)

KEYCODE_CTRL_RIGHT
Added in API level 11
public static final int KEYCODE_CTRL_RIGHT
Key code constant: Right Control modifier key.

Constant Value: 114 (0x00000072)

KEYCODE_CUT
Added in API level 24
public static final int KEYCODE_CUT
Key code constant: Cut key.

Constant Value: 277 (0x00000115)

KEYCODE_D
Added in API level 1
public static final int KEYCODE_D
Key code constant: 'D' key.

Constant Value: 32 (0x00000020)

KEYCODE_DEL
public static final int KEYCODE_DEL
Key code constant: Backspace key. Deletes characters before the insertion point, unlike KEYCODE_FORWARD_DEL. * @apiSince 1

Constant Value: 67 (0x00000043)

KEYCODE_DPAD_CENTER
public static final int KEYCODE_DPAD_CENTER
Key code constant: Directional Pad Center key. May also be synthesized from trackball motions. * @apiSince 1

Constant Value: 23 (0x00000017)

KEYCODE_DPAD_DOWN
public static final int KEYCODE_DPAD_DOWN
Key code constant: Directional Pad Down key. May also be synthesized from trackball motions. * @apiSince 1

Constant Value: 20 (0x00000014)

KEYCODE_DPAD_DOWN_LEFT
Added in API level 24
public static final int KEYCODE_DPAD_DOWN_LEFT
Key code constant: Directional Pad Down-Left

Constant Value: 269 (0x0000010d)

KEYCODE_DPAD_DOWN_RIGHT
Added in API level 24
public static final int KEYCODE_DPAD_DOWN_RIGHT
Key code constant: Directional Pad Down-Right

Constant Value: 271 (0x0000010f)

KEYCODE_DPAD_LEFT
public static final int KEYCODE_DPAD_LEFT
Key code constant: Directional Pad Left key. May also be synthesized from trackball motions. * @apiSince 1

Constant Value: 21 (0x00000015)

KEYCODE_DPAD_RIGHT
public static final int KEYCODE_DPAD_RIGHT
Key code constant: Directional Pad Right key. May also be synthesized from trackball motions. * @apiSince 1

Constant Value: 22 (0x00000016)

KEYCODE_DPAD_UP
public static final int KEYCODE_DPAD_UP
Key code constant: Directional Pad Up key. May also be synthesized from trackball motions. * @apiSince 1

Constant Value: 19 (0x00000013)

KEYCODE_DPAD_UP_LEFT
Added in API level 24
public static final int KEYCODE_DPAD_UP_LEFT
Key code constant: Directional Pad Up-Left

Constant Value: 268 (0x0000010c)

KEYCODE_DPAD_UP_RIGHT
Added in API level 24
public static final int KEYCODE_DPAD_UP_RIGHT
Key code constant: Directional Pad Up-Right

Constant Value: 270 (0x0000010e)

KEYCODE_DVR
public static final int KEYCODE_DVR
Key code constant: DVR key. On some TV remotes, switches to a DVR mode for recorded shows. * @apiSince 11

Constant Value: 173 (0x000000ad)

KEYCODE_E
Added in API level 1
public static final int KEYCODE_E
Key code constant: 'E' key.

Constant Value: 33 (0x00000021)

KEYCODE_EISU
Added in API level 16
public static final int KEYCODE_EISU
Key code constant: Japanese alphanumeric key.

Constant Value: 212 (0x000000d4)

KEYCODE_ENDCALL
Added in API level 1
public static final int KEYCODE_ENDCALL
Key code constant: End Call key.

Constant Value: 6 (0x00000006)

KEYCODE_ENTER
Added in API level 1
public static final int KEYCODE_ENTER
Key code constant: Enter key.

Constant Value: 66 (0x00000042)

KEYCODE_ENVELOPE
public static final int KEYCODE_ENVELOPE
Key code constant: Envelope special function key. Used to launch a mail application. * @apiSince 1

Constant Value: 65 (0x00000041)

KEYCODE_EQUALS
Added in API level 1
public static final int KEYCODE_EQUALS
Key code constant: '=' key.

Constant Value: 70 (0x00000046)

KEYCODE_ESCAPE
Added in API level 11
public static final int KEYCODE_ESCAPE
Key code constant: Escape key.

Constant Value: 111 (0x0000006f)

KEYCODE_EXPLORER
public static final int KEYCODE_EXPLORER
Key code constant: Explorer special function key. Used to launch a browser application. * @apiSince 1

Constant Value: 64 (0x00000040)

KEYCODE_F
Added in API level 1
public static final int KEYCODE_F
Key code constant: 'F' key.

Constant Value: 34 (0x00000022)

KEYCODE_F1
Added in API level 11
public static final int KEYCODE_F1
Key code constant: F1 key.

Constant Value: 131 (0x00000083)

KEYCODE_F10
Added in API level 11
public static final int KEYCODE_F10
Key code constant: F10 key.

Constant Value: 140 (0x0000008c)

KEYCODE_F11
Added in API level 11
public static final int KEYCODE_F11
Key code constant: F11 key.

Constant Value: 141 (0x0000008d)

KEYCODE_F12
Added in API level 11
public static final int KEYCODE_F12
Key code constant: F12 key.

Constant Value: 142 (0x0000008e)

KEYCODE_F2
Added in API level 11
public static final int KEYCODE_F2
Key code constant: F2 key.

Constant Value: 132 (0x00000084)

KEYCODE_F3
Added in API level 11
public static final int KEYCODE_F3
Key code constant: F3 key.

Constant Value: 133 (0x00000085)

KEYCODE_F4
Added in API level 11
public static final int KEYCODE_F4
Key code constant: F4 key.

Constant Value: 134 (0x00000086)

KEYCODE_F5
Added in API level 11
public static final int KEYCODE_F5
Key code constant: F5 key.

Constant Value: 135 (0x00000087)

KEYCODE_F6
Added in API level 11
public static final int KEYCODE_F6
Key code constant: F6 key.

Constant Value: 136 (0x00000088)

KEYCODE_F7
Added in API level 11
public static final int KEYCODE_F7
Key code constant: F7 key.

Constant Value: 137 (0x00000089)

KEYCODE_F8
Added in API level 11
public static final int KEYCODE_F8
Key code constant: F8 key.

Constant Value: 138 (0x0000008a)

KEYCODE_F9
Added in API level 11
public static final int KEYCODE_F9
Key code constant: F9 key.

Constant Value: 139 (0x0000008b)

KEYCODE_FOCUS
public static final int KEYCODE_FOCUS
Key code constant: Camera Focus key. Used to focus the camera. * @apiSince 1

Constant Value: 80 (0x00000050)

KEYCODE_FORWARD
public static final int KEYCODE_FORWARD
Key code constant: Forward key. Navigates forward in the history stack. Complement of KEYCODE_BACK. * @apiSince 11

Constant Value: 125 (0x0000007d)

KEYCODE_FORWARD_DEL
public static final int KEYCODE_FORWARD_DEL
Key code constant: Forward Delete key. Deletes characters ahead of the insertion point, unlike KEYCODE_DEL. * @apiSince 11

Constant Value: 112 (0x00000070)

KEYCODE_FUNCTION
Added in API level 11
public static final int KEYCODE_FUNCTION
Key code constant: Function modifier key.

Constant Value: 119 (0x00000077)

KEYCODE_G
Added in API level 1
public static final int KEYCODE_G
Key code constant: 'G' key.

Constant Value: 35 (0x00000023)

KEYCODE_GRAVE
Added in API level 1
public static final int KEYCODE_GRAVE
Key code constant: '`' (backtick) key.

Constant Value: 68 (0x00000044)

KEYCODE_GUIDE
public static final int KEYCODE_GUIDE
Key code constant: Guide key. On TV remotes, shows a programming guide. * @apiSince 11

Constant Value: 172 (0x000000ac)

KEYCODE_H
Added in API level 1
public static final int KEYCODE_H
Key code constant: 'H' key.

Constant Value: 36 (0x00000024)

KEYCODE_HEADSETHOOK
public static final int KEYCODE_HEADSETHOOK
Key code constant: Headset Hook key. Used to hang up calls and stop media. * @apiSince 1

Constant Value: 79 (0x0000004f)

KEYCODE_HELP
Added in API level 21
public static final int KEYCODE_HELP
Key code constant: Help key.

Constant Value: 259 (0x00000103)

KEYCODE_HENKAN
Added in API level 16
public static final int KEYCODE_HENKAN
Key code constant: Japanese conversion key.

Constant Value: 214 (0x000000d6)

KEYCODE_HOME
public static final int KEYCODE_HOME
Key code constant: Home key. This key is handled by the framework and is never delivered to applications. * @apiSince 1

Constant Value: 3 (0x00000003)

KEYCODE_I
Added in API level 1
public static final int KEYCODE_I
Key code constant: 'I' key.

Constant Value: 37 (0x00000025)

KEYCODE_INFO
public static final int KEYCODE_INFO
Key code constant: Info key. Common on TV remotes to show additional information related to what is currently being viewed. * @apiSince 11

Constant Value: 165 (0x000000a5)

KEYCODE_INSERT
public static final int KEYCODE_INSERT
Key code constant: Insert key. Toggles insert / overwrite edit mode. * @apiSince 11

Constant Value: 124 (0x0000007c)

KEYCODE_J
Added in API level 1
public static final int KEYCODE_J
Key code constant: 'J' key.

Constant Value: 38 (0x00000026)

KEYCODE_K
Added in API level 1
public static final int KEYCODE_K
Key code constant: 'K' key.

Constant Value: 39 (0x00000027)

KEYCODE_KANA
Added in API level 16
public static final int KEYCODE_KANA
Key code constant: Japanese kana key.

Constant Value: 218 (0x000000da)

KEYCODE_KATAKANA_HIRAGANA
Added in API level 16
public static final int KEYCODE_KATAKANA_HIRAGANA
Key code constant: Japanese katakana / hiragana key.

Constant Value: 215 (0x000000d7)

KEYCODE_L
Added in API level 1
public static final int KEYCODE_L
Key code constant: 'L' key.

Constant Value: 40 (0x00000028)

KEYCODE_LANGUAGE_SWITCH
public static final int KEYCODE_LANGUAGE_SWITCH
Key code constant: Language Switch key. Toggles the current input language such as switching between English and Japanese on a QWERTY keyboard. On some devices, the same function may be performed by pressing Shift+Spacebar. * @apiSince 14

Constant Value: 204 (0x000000cc)

KEYCODE_LAST_CHANNEL
public static final int KEYCODE_LAST_CHANNEL
Key code constant: Last Channel key. Goes to the last viewed channel. * @apiSince 21

Constant Value: 229 (0x000000e5)

KEYCODE_LEFT_BRACKET
Added in API level 1
public static final int KEYCODE_LEFT_BRACKET
Key code constant: '[' key.

Constant Value: 71 (0x00000047)

KEYCODE_M
Added in API level 1
public static final int KEYCODE_M
Key code constant: 'M' key.

Constant Value: 41 (0x00000029)

KEYCODE_MANNER_MODE
public static final int KEYCODE_MANNER_MODE
Key code constant: Manner Mode key. Toggles silent or vibrate mode on and off to make the device behave more politely in certain settings such as on a crowded train. On some devices, the key may only operate when long-pressed. * @apiSince 14

Constant Value: 205 (0x000000cd)

KEYCODE_MEDIA_AUDIO_TRACK
public static final int KEYCODE_MEDIA_AUDIO_TRACK
Key code constant: Audio Track key. Switches the audio tracks. * @apiSince 19

Constant Value: 222 (0x000000de)

KEYCODE_MEDIA_CLOSE
public static final int KEYCODE_MEDIA_CLOSE
Key code constant: Close media key. May be used to close a CD tray, for example. * @apiSince 11

Constant Value: 128 (0x00000080)

KEYCODE_MEDIA_EJECT
public static final int KEYCODE_MEDIA_EJECT
Key code constant: Eject media key. May be used to eject a CD tray, for example. * @apiSince 11

Constant Value: 129 (0x00000081)

KEYCODE_MEDIA_FAST_FORWARD
Added in API level 3
public static final int KEYCODE_MEDIA_FAST_FORWARD
Key code constant: Fast Forward media key.

Constant Value: 90 (0x0000005a)

KEYCODE_MEDIA_NEXT
Added in API level 3
public static final int KEYCODE_MEDIA_NEXT
Key code constant: Play Next media key.

Constant Value: 87 (0x00000057)

KEYCODE_MEDIA_PAUSE
Added in API level 11
public static final int KEYCODE_MEDIA_PAUSE
Key code constant: Pause media key.

Constant Value: 127 (0x0000007f)

KEYCODE_MEDIA_PLAY
Added in API level 11
public static final int KEYCODE_MEDIA_PLAY
Key code constant: Play media key.

Constant Value: 126 (0x0000007e)

KEYCODE_MEDIA_PLAY_PAUSE
Added in API level 3
public static final int KEYCODE_MEDIA_PLAY_PAUSE
Key code constant: Play/Pause media key.

Constant Value: 85 (0x00000055)

KEYCODE_MEDIA_PREVIOUS
Added in API level 3
public static final int KEYCODE_MEDIA_PREVIOUS
Key code constant: Play Previous media key.

Constant Value: 88 (0x00000058)

KEYCODE_MEDIA_RECORD
Added in API level 11
public static final int KEYCODE_MEDIA_RECORD
Key code constant: Record media key.

Constant Value: 130 (0x00000082)

KEYCODE_MEDIA_REWIND
Added in API level 3
public static final int KEYCODE_MEDIA_REWIND
Key code constant: Rewind media key.

Constant Value: 89 (0x00000059)

KEYCODE_MEDIA_SKIP_BACKWARD
Added in API level 23
public static final int KEYCODE_MEDIA_SKIP_BACKWARD
Key code constant: Skip backward media key.

Constant Value: 273 (0x00000111)

KEYCODE_MEDIA_SKIP_FORWARD
Added in API level 23
public static final int KEYCODE_MEDIA_SKIP_FORWARD
Key code constant: Skip forward media key.

Constant Value: 272 (0x00000110)

KEYCODE_MEDIA_STEP_BACKWARD
public static final int KEYCODE_MEDIA_STEP_BACKWARD
Key code constant: Step backward media key. Steps media backward, one frame at a time. * @apiSince 23

Constant Value: 275 (0x00000113)

KEYCODE_MEDIA_STEP_FORWARD
public static final int KEYCODE_MEDIA_STEP_FORWARD
Key code constant: Step forward media key. Steps media forward, one frame at a time. * @apiSince 23

Constant Value: 274 (0x00000112)

KEYCODE_MEDIA_STOP
Added in API level 3
public static final int KEYCODE_MEDIA_STOP
Key code constant: Stop media key.

Constant Value: 86 (0x00000056)

KEYCODE_MEDIA_TOP_MENU
public static final int KEYCODE_MEDIA_TOP_MENU
Key code constant: Media Top Menu key. Goes to the top of media menu. * @apiSince 21

Constant Value: 226 (0x000000e2)

KEYCODE_MENU
Added in API level 1
public static final int KEYCODE_MENU
Key code constant: Menu key.

Constant Value: 82 (0x00000052)

KEYCODE_META_LEFT
Added in API level 11
public static final int KEYCODE_META_LEFT
Key code constant: Left Meta modifier key.

Constant Value: 117 (0x00000075)

KEYCODE_META_RIGHT
Added in API level 11
public static final int KEYCODE_META_RIGHT
Key code constant: Right Meta modifier key.

Constant Value: 118 (0x00000076)

KEYCODE_MINUS
Added in API level 1
public static final int KEYCODE_MINUS
Key code constant: '-'.

Constant Value: 69 (0x00000045)

KEYCODE_MOVE_END
public static final int KEYCODE_MOVE_END
Key code constant: End Movement key. Used for scrolling or moving the cursor around to the end of a line or to the bottom of a list. * @apiSince 11

Constant Value: 123 (0x0000007b)

KEYCODE_MOVE_HOME
public static final int KEYCODE_MOVE_HOME
Key code constant: Home Movement key. Used for scrolling or moving the cursor around to the start of a line or to the top of a list. * @apiSince 11

Constant Value: 122 (0x0000007a)

KEYCODE_MUHENKAN
Added in API level 16
public static final int KEYCODE_MUHENKAN
Key code constant: Japanese non-conversion key.

Constant Value: 213 (0x000000d5)

KEYCODE_MUSIC
public static final int KEYCODE_MUSIC
Key code constant: Music special function key. Used to launch a music player application. * @apiSince 15

Constant Value: 209 (0x000000d1)

KEYCODE_MUTE
public static final int KEYCODE_MUTE
Key code constant: Mute key. Mutes the microphone, unlike KEYCODE_VOLUME_MUTE. * @apiSince 3

Constant Value: 91 (0x0000005b)

KEYCODE_N
Added in API level 1
public static final int KEYCODE_N
Key code constant: 'N' key.

Constant Value: 42 (0x0000002a)

KEYCODE_NAVIGATE_IN
public static final int KEYCODE_NAVIGATE_IN
Key code constant: Navigate in key. Activates the item that currently has focus or expands to the next level of a navigation hierarchy. * @apiSince 23

Constant Value: 262 (0x00000106)

KEYCODE_NAVIGATE_NEXT
public static final int KEYCODE_NAVIGATE_NEXT
Key code constant: Navigate to next key. Advances to the next item in an ordered collection of items. * @apiSince 23

Constant Value: 261 (0x00000105)

KEYCODE_NAVIGATE_OUT
public static final int KEYCODE_NAVIGATE_OUT
Key code constant: Navigate out key. Backs out one level of a navigation hierarchy or collapses the item that currently has focus. * @apiSince 23

Constant Value: 263 (0x00000107)

KEYCODE_NAVIGATE_PREVIOUS
public static final int KEYCODE_NAVIGATE_PREVIOUS
Key code constant: Navigate to previous key. Goes backward by one item in an ordered collection of items. * @apiSince 23

Constant Value: 260 (0x00000104)

KEYCODE_NOTIFICATION
Added in API level 1
public static final int KEYCODE_NOTIFICATION
Key code constant: Notification key.

Constant Value: 83 (0x00000053)

KEYCODE_NUM
public static final int KEYCODE_NUM
Key code constant: Number modifier key. Used to enter numeric symbols. This key is not Num Lock; it is more like KEYCODE_ALT_LEFT and is interpreted as an ALT key by MetaKeyKeyListener. * @apiSince 1

Constant Value: 78 (0x0000004e)

KEYCODE_NUMPAD_0
Added in API level 11
public static final int KEYCODE_NUMPAD_0
Key code constant: Numeric keypad '0' key.

Constant Value: 144 (0x00000090)

KEYCODE_NUMPAD_1
Added in API level 11
public static final int KEYCODE_NUMPAD_1
Key code constant: Numeric keypad '1' key.

Constant Value: 145 (0x00000091)

KEYCODE_NUMPAD_2
Added in API level 11
public static final int KEYCODE_NUMPAD_2
Key code constant: Numeric keypad '2' key.

Constant Value: 146 (0x00000092)

KEYCODE_NUMPAD_3
Added in API level 11
public static final int KEYCODE_NUMPAD_3
Key code constant: Numeric keypad '3' key.

Constant Value: 147 (0x00000093)

KEYCODE_NUMPAD_4
Added in API level 11
public static final int KEYCODE_NUMPAD_4
Key code constant: Numeric keypad '4' key.

Constant Value: 148 (0x00000094)

KEYCODE_NUMPAD_5
Added in API level 11
public static final int KEYCODE_NUMPAD_5
Key code constant: Numeric keypad '5' key.

Constant Value: 149 (0x00000095)

KEYCODE_NUMPAD_6
Added in API level 11
public static final int KEYCODE_NUMPAD_6
Key code constant: Numeric keypad '6' key.

Constant Value: 150 (0x00000096)

KEYCODE_NUMPAD_7
Added in API level 11
public static final int KEYCODE_NUMPAD_7
Key code constant: Numeric keypad '7' key.

Constant Value: 151 (0x00000097)

KEYCODE_NUMPAD_8
Added in API level 11
public static final int KEYCODE_NUMPAD_8
Key code constant: Numeric keypad '8' key.

Constant Value: 152 (0x00000098)

KEYCODE_NUMPAD_9
Added in API level 11
public static final int KEYCODE_NUMPAD_9
Key code constant: Numeric keypad '9' key.

Constant Value: 153 (0x00000099)

KEYCODE_NUMPAD_ADD
Added in API level 11
public static final int KEYCODE_NUMPAD_ADD
Key code constant: Numeric keypad '+' key (for addition).

Constant Value: 157 (0x0000009d)

KEYCODE_NUMPAD_COMMA
Added in API level 11
public static final int KEYCODE_NUMPAD_COMMA
Key code constant: Numeric keypad ',' key (for decimals or digit grouping).

Constant Value: 159 (0x0000009f)

KEYCODE_NUMPAD_DIVIDE
Added in API level 11
public static final int KEYCODE_NUMPAD_DIVIDE
Key code constant: Numeric keypad '/' key (for division).

Constant Value: 154 (0x0000009a)

KEYCODE_NUMPAD_DOT
Added in API level 11
public static final int KEYCODE_NUMPAD_DOT
Key code constant: Numeric keypad '.' key (for decimals or digit grouping).

Constant Value: 158 (0x0000009e)

KEYCODE_NUMPAD_ENTER
Added in API level 11
public static final int KEYCODE_NUMPAD_ENTER
Key code constant: Numeric keypad Enter key.

Constant Value: 160 (0x000000a0)

KEYCODE_NUMPAD_EQUALS
Added in API level 11
public static final int KEYCODE_NUMPAD_EQUALS
Key code constant: Numeric keypad '=' key.

Constant Value: 161 (0x000000a1)

KEYCODE_NUMPAD_LEFT_PAREN
Added in API level 11
public static final int KEYCODE_NUMPAD_LEFT_PAREN
Key code constant: Numeric keypad '(' key.

Constant Value: 162 (0x000000a2)

KEYCODE_NUMPAD_MULTIPLY
Added in API level 11
public static final int KEYCODE_NUMPAD_MULTIPLY
Key code constant: Numeric keypad '*' key (for multiplication).

Constant Value: 155 (0x0000009b)

KEYCODE_NUMPAD_RIGHT_PAREN
Added in API level 11
public static final int KEYCODE_NUMPAD_RIGHT_PAREN
Key code constant: Numeric keypad ')' key.

Constant Value: 163 (0x000000a3)

KEYCODE_NUMPAD_SUBTRACT
Added in API level 11
public static final int KEYCODE_NUMPAD_SUBTRACT
Key code constant: Numeric keypad '-' key (for subtraction).

Constant Value: 156 (0x0000009c)

KEYCODE_NUM_LOCK
public static final int KEYCODE_NUM_LOCK
Key code constant: Num Lock key. This is the Num Lock key; it is different from KEYCODE_NUM. This key alters the behavior of other keys on the numeric keypad. * @apiSince 11

Constant Value: 143 (0x0000008f)

KEYCODE_O
Added in API level 1
public static final int KEYCODE_O
Key code constant: 'O' key.

Constant Value: 43 (0x0000002b)

KEYCODE_P
Added in API level 1
public static final int KEYCODE_P
Key code constant: 'P' key.

Constant Value: 44 (0x0000002c)

KEYCODE_PAGE_DOWN
Added in API level 9
public static final int KEYCODE_PAGE_DOWN
Key code constant: Page Down key.

Constant Value: 93 (0x0000005d)

KEYCODE_PAGE_UP
Added in API level 9
public static final int KEYCODE_PAGE_UP
Key code constant: Page Up key.

Constant Value: 92 (0x0000005c)

KEYCODE_PAIRING
public static final int KEYCODE_PAIRING
Key code constant: Pairing key. Initiates peripheral pairing mode. Useful for pairing remote control devices or game controllers, especially if no other input mode is available. * @apiSince 21

Constant Value: 225 (0x000000e1)

KEYCODE_PASTE
Added in API level 24
public static final int KEYCODE_PASTE
Key code constant: Paste key.

Constant Value: 279 (0x00000117)

KEYCODE_PERIOD
Added in API level 1
public static final int KEYCODE_PERIOD
Key code constant: '.' key.

Constant Value: 56 (0x00000038)

KEYCODE_PICTSYMBOLS
public static final int KEYCODE_PICTSYMBOLS
Key code constant: Picture Symbols modifier key. Used to switch symbol sets (Emoji, Kao-moji). * @apiSince 9

Constant Value: 94 (0x0000005e)

KEYCODE_PLUS
Added in API level 1
public static final int KEYCODE_PLUS
Key code constant: '+' key.

Constant Value: 81 (0x00000051)

KEYCODE_POUND
Added in API level 1
public static final int KEYCODE_POUND
Key code constant: '#' key.

Constant Value: 18 (0x00000012)

KEYCODE_POWER
Added in API level 1
public static final int KEYCODE_POWER
Key code constant: Power key.

Constant Value: 26 (0x0000001a)

KEYCODE_PROFILE_SWITCH
Added in API level 29
public static final int KEYCODE_PROFILE_SWITCH
Key code constant: Used to switch current Account that is consuming content. May be consumed by system to set account globally.

Constant Value: 288 (0x00000120)

KEYCODE_PROG_BLUE
public static final int KEYCODE_PROG_BLUE
Key code constant: Blue "programmable" key. On TV remotes, acts as a contextual/programmable key. * @apiSince 11

Constant Value: 186 (0x000000ba)

KEYCODE_PROG_GREEN
public static final int KEYCODE_PROG_GREEN
Key code constant: Green "programmable" key. On TV remotes, actsas a contextual/programmable key. * @apiSince 11

Constant Value: 184 (0x000000b8)

KEYCODE_PROG_RED
public static final int KEYCODE_PROG_RED
Key code constant: Red "programmable" key. On TV remotes, acts as a contextual/programmable key. * @apiSince 11

Constant Value: 183 (0x000000b7)

KEYCODE_PROG_YELLOW
public static final int KEYCODE_PROG_YELLOW
Key code constant: Yellow "programmable" key. On TV remotes, acts as a contextual/programmable key. * @apiSince 11

Constant Value: 185 (0x000000b9)

KEYCODE_Q
Added in API level 1
public static final int KEYCODE_Q
Key code constant: 'Q' key.

Constant Value: 45 (0x0000002d)

KEYCODE_R
Added in API level 1
public static final int KEYCODE_R
Key code constant: 'R' key.

Constant Value: 46 (0x0000002e)

KEYCODE_REFRESH
Added in API level 28
public static final int KEYCODE_REFRESH
Key code constant: Refresh key.

Constant Value: 285 (0x0000011d)

KEYCODE_RIGHT_BRACKET
Added in API level 1
public static final int KEYCODE_RIGHT_BRACKET
Key code constant: ']' key.

Constant Value: 72 (0x00000048)

KEYCODE_RO
Added in API level 16
public static final int KEYCODE_RO
Key code constant: Japanese Ro key.

Constant Value: 217 (0x000000d9)

KEYCODE_S
Added in API level 1
public static final int KEYCODE_S
Key code constant: 'S' key.

Constant Value: 47 (0x0000002f)

KEYCODE_SCROLL_LOCK
Added in API level 11
public static final int KEYCODE_SCROLL_LOCK
Key code constant: Scroll Lock key.

Constant Value: 116 (0x00000074)

KEYCODE_SEARCH
Added in API level 1
public static final int KEYCODE_SEARCH
Key code constant: Search key.

Constant Value: 84 (0x00000054)

KEYCODE_SEMICOLON
Added in API level 1
public static final int KEYCODE_SEMICOLON
Key code constant: ';' key.

Constant Value: 74 (0x0000004a)

KEYCODE_SETTINGS
public static final int KEYCODE_SETTINGS
Key code constant: Settings key. Starts the system settings activity. * @apiSince 11

Constant Value: 176 (0x000000b0)

KEYCODE_SHIFT_LEFT
Added in API level 1
public static final int KEYCODE_SHIFT_LEFT
Key code constant: Left Shift modifier key.

Constant Value: 59 (0x0000003b)

KEYCODE_SHIFT_RIGHT
Added in API level 1
public static final int KEYCODE_SHIFT_RIGHT
Key code constant: Right Shift modifier key.

Constant Value: 60 (0x0000003c)

KEYCODE_SLASH
Added in API level 1
public static final int KEYCODE_SLASH
Key code constant: '/' key.

Constant Value: 76 (0x0000004c)

KEYCODE_SLEEP
public static final int KEYCODE_SLEEP
Key code constant: Sleep key. Puts the device to sleep. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already asleep. * @apiSince 20

Constant Value: 223 (0x000000df)

KEYCODE_SOFT_LEFT
public static final int KEYCODE_SOFT_LEFT
Key code constant: Soft Left key. Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom left of the display. * @apiSince 1

Constant Value: 1 (0x00000001)

KEYCODE_SOFT_RIGHT
public static final int KEYCODE_SOFT_RIGHT
Key code constant: Soft Right key. Usually situated below the display on phones and used as a multi-function feature key for selecting a software defined function shown on the bottom right of the display. * @apiSince 1

Constant Value: 2 (0x00000002)

KEYCODE_SOFT_SLEEP
Added in API level 24
public static final int KEYCODE_SOFT_SLEEP
Key code constant: put device to sleep unless a wakelock is held.

Constant Value: 276 (0x00000114)

KEYCODE_SPACE
Added in API level 1
public static final int KEYCODE_SPACE
Key code constant: Space key.

Constant Value: 62 (0x0000003e)

KEYCODE_STAR
Added in API level 1
public static final int KEYCODE_STAR
Key code constant: '*' key.

Constant Value: 17 (0x00000011)

KEYCODE_STB_INPUT
public static final int KEYCODE_STB_INPUT
Key code constant: Set-top-box input key. On TV remotes, switches the input mode on an external Set-top-box. * @apiSince 11

Constant Value: 180 (0x000000b4)

KEYCODE_STB_POWER
public static final int KEYCODE_STB_POWER
Key code constant: Set-top-box power key. On TV remotes, toggles the power on an external Set-top-box. * @apiSince 11

Constant Value: 179 (0x000000b3)

KEYCODE_STEM_1
Added in API level 24
public static final int KEYCODE_STEM_1
Key code constant: Generic stem key 1 for Wear

Constant Value: 265 (0x00000109)

KEYCODE_STEM_2
Added in API level 24
public static final int KEYCODE_STEM_2
Key code constant: Generic stem key 2 for Wear

Constant Value: 266 (0x0000010a)

KEYCODE_STEM_3
Added in API level 24
public static final int KEYCODE_STEM_3
Key code constant: Generic stem key 3 for Wear

Constant Value: 267 (0x0000010b)

KEYCODE_STEM_PRIMARY
public static final int KEYCODE_STEM_PRIMARY
Key code constant: Primary stem key for Wear Main power/reset button on watch. * @apiSince 24

Constant Value: 264 (0x00000108)

KEYCODE_SWITCH_CHARSET
public static final int KEYCODE_SWITCH_CHARSET
Key code constant: Switch Charset modifier key. Used to switch character sets (Kanji, Katakana). * @apiSince 9

Constant Value: 95 (0x0000005f)

KEYCODE_SYM
public static final int KEYCODE_SYM
Key code constant: Symbol modifier key. Used to enter alternate symbols. * @apiSince 1

Constant Value: 63 (0x0000003f)

KEYCODE_SYSRQ
Added in API level 11
public static final int KEYCODE_SYSRQ
Key code constant: System Request / Print Screen key.

Constant Value: 120 (0x00000078)

KEYCODE_SYSTEM_NAVIGATION_DOWN
Added in API level 25
public static final int KEYCODE_SYSTEM_NAVIGATION_DOWN
Key code constant: Consumed by the system for navigation down

Constant Value: 281 (0x00000119)

KEYCODE_SYSTEM_NAVIGATION_LEFT
Added in API level 25
public static final int KEYCODE_SYSTEM_NAVIGATION_LEFT
Key code constant: Consumed by the system for navigation left

Constant Value: 282 (0x0000011a)

KEYCODE_SYSTEM_NAVIGATION_RIGHT
Added in API level 25
public static final int KEYCODE_SYSTEM_NAVIGATION_RIGHT
Key code constant: Consumed by the system for navigation right

Constant Value: 283 (0x0000011b)

KEYCODE_SYSTEM_NAVIGATION_UP
Added in API level 25
public static final int KEYCODE_SYSTEM_NAVIGATION_UP
Key code constant: Consumed by the system for navigation up

Constant Value: 280 (0x00000118)

KEYCODE_T
Added in API level 1
public static final int KEYCODE_T
Key code constant: 'T' key.

Constant Value: 48 (0x00000030)

KEYCODE_TAB
Added in API level 1
public static final int KEYCODE_TAB
Key code constant: Tab key.

Constant Value: 61 (0x0000003d)

KEYCODE_THUMBS_DOWN
Added in API level 29
public static final int KEYCODE_THUMBS_DOWN
Key code constant: Thumbs down key. Apps can use this to let user downvote content.

Constant Value: 287 (0x0000011f)

KEYCODE_THUMBS_UP
Added in API level 29
public static final int KEYCODE_THUMBS_UP
Key code constant: Thumbs up key. Apps can use this to let user upvote content.

Constant Value: 286 (0x0000011e)

KEYCODE_TV
public static final int KEYCODE_TV
Key code constant: TV key. On TV remotes, switches to viewing live TV. * @apiSince 11

Constant Value: 170 (0x000000aa)

KEYCODE_TV_ANTENNA_CABLE
public static final int KEYCODE_TV_ANTENNA_CABLE
Key code constant: Antenna/Cable key. Toggles broadcast input source between antenna and cable. * @apiSince 21

Constant Value: 242 (0x000000f2)

KEYCODE_TV_AUDIO_DESCRIPTION
public static final int KEYCODE_TV_AUDIO_DESCRIPTION
Key code constant: Audio description key. Toggles audio description off / on. * @apiSince 21

Constant Value: 252 (0x000000fc)

KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN
public static final int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN
Key code constant: Audio description mixing volume down key. Lessen audio description volume as compared with normal audio volume. * @apiSince 21

Constant Value: 254 (0x000000fe)

KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP
public static final int KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP
Key code constant: Audio description mixing volume up key. Louden audio description volume as compared with normal audio volume. * @apiSince 21

Constant Value: 253 (0x000000fd)

KEYCODE_TV_CONTENTS_MENU
public static final int KEYCODE_TV_CONTENTS_MENU
Key code constant: Contents menu key. Goes to the title list. Corresponds to Contents Menu (0x0B) of CEC User Control Code * @apiSince 21

Constant Value: 256 (0x00000100)

KEYCODE_TV_DATA_SERVICE
public static final int KEYCODE_TV_DATA_SERVICE
Key code constant: TV data service key. Displays data services like weather, sports. * @apiSince 21

Constant Value: 230 (0x000000e6)

KEYCODE_TV_INPUT
public static final int KEYCODE_TV_INPUT
Key code constant: TV input key. On TV remotes, switches the input on a television screen. * @apiSince 11

Constant Value: 178 (0x000000b2)

KEYCODE_TV_INPUT_COMPONENT_1
public static final int KEYCODE_TV_INPUT_COMPONENT_1
Key code constant: Component #1 key. Switches to component video input #1. * @apiSince 21

Constant Value: 249 (0x000000f9)

KEYCODE_TV_INPUT_COMPONENT_2
public static final int KEYCODE_TV_INPUT_COMPONENT_2
Key code constant: Component #2 key. Switches to component video input #2. * @apiSince 21

Constant Value: 250 (0x000000fa)

KEYCODE_TV_INPUT_COMPOSITE_1
public static final int KEYCODE_TV_INPUT_COMPOSITE_1
Key code constant: Composite #1 key. Switches to composite video input #1. * @apiSince 21

Constant Value: 247 (0x000000f7)

KEYCODE_TV_INPUT_COMPOSITE_2
public static final int KEYCODE_TV_INPUT_COMPOSITE_2
Key code constant: Composite #2 key. Switches to composite video input #2. * @apiSince 21

Constant Value: 248 (0x000000f8)

KEYCODE_TV_INPUT_HDMI_1
public static final int KEYCODE_TV_INPUT_HDMI_1
Key code constant: HDMI #1 key. Switches to HDMI input #1. * @apiSince 21

Constant Value: 243 (0x000000f3)

KEYCODE_TV_INPUT_HDMI_2
public static final int KEYCODE_TV_INPUT_HDMI_2
Key code constant: HDMI #2 key. Switches to HDMI input #2. * @apiSince 21

Constant Value: 244 (0x000000f4)

KEYCODE_TV_INPUT_HDMI_3
public static final int KEYCODE_TV_INPUT_HDMI_3
Key code constant: HDMI #3 key. Switches to HDMI input #3. * @apiSince 21

Constant Value: 245 (0x000000f5)

KEYCODE_TV_INPUT_HDMI_4
public static final int KEYCODE_TV_INPUT_HDMI_4
Key code constant: HDMI #4 key. Switches to HDMI input #4. * @apiSince 21

Constant Value: 246 (0x000000f6)

KEYCODE_TV_INPUT_VGA_1
public static final int KEYCODE_TV_INPUT_VGA_1
Key code constant: VGA #1 key. Switches to VGA (analog RGB) input #1. * @apiSince 21

Constant Value: 251 (0x000000fb)

KEYCODE_TV_MEDIA_CONTEXT_MENU
public static final int KEYCODE_TV_MEDIA_CONTEXT_MENU
Key code constant: Media context menu key. Goes to the context menu of media contents. Corresponds to Media Context-sensitive Menu (0x11) of CEC User Control Code. * @apiSince 21

Constant Value: 257 (0x00000101)

KEYCODE_TV_NETWORK
public static final int KEYCODE_TV_NETWORK
Key code constant: Toggle Network key. Toggles selecting broacast services. * @apiSince 21

Constant Value: 241 (0x000000f1)

KEYCODE_TV_NUMBER_ENTRY
public static final int KEYCODE_TV_NUMBER_ENTRY
Key code constant: Number entry key. Initiates to enter multi-digit channel nubmber when each digit key is assigned for selecting separate channel. Corresponds to Number Entry Mode (0x1D) of CEC User Control Code. * @apiSince 21

Constant Value: 234 (0x000000ea)

KEYCODE_TV_POWER
public static final int KEYCODE_TV_POWER
Key code constant: TV power key. On TV remotes, toggles the power on a television screen. * @apiSince 11

Constant Value: 177 (0x000000b1)

KEYCODE_TV_RADIO_SERVICE
public static final int KEYCODE_TV_RADIO_SERVICE
Key code constant: Radio key. Toggles TV service / Radio service. * @apiSince 21

Constant Value: 232 (0x000000e8)

KEYCODE_TV_SATELLITE
public static final int KEYCODE_TV_SATELLITE
Key code constant: Satellite key. Switches to digital satellite broadcast service. * @apiSince 21

Constant Value: 237 (0x000000ed)

KEYCODE_TV_SATELLITE_BS
public static final int KEYCODE_TV_SATELLITE_BS
Key code constant: BS key. Switches to BS digital satellite broadcasting service available in Japan. * @apiSince 21

Constant Value: 238 (0x000000ee)

KEYCODE_TV_SATELLITE_CS
public static final int KEYCODE_TV_SATELLITE_CS
Key code constant: CS key. Switches to CS digital satellite broadcasting service available in Japan. * @apiSince 21

Constant Value: 239 (0x000000ef)

KEYCODE_TV_SATELLITE_SERVICE
public static final int KEYCODE_TV_SATELLITE_SERVICE
Key code constant: BS/CS key. Toggles between BS and CS digital satellite services. * @apiSince 21

Constant Value: 240 (0x000000f0)

KEYCODE_TV_TELETEXT
public static final int KEYCODE_TV_TELETEXT
Key code constant: Teletext key. Displays Teletext service. * @apiSince 21

Constant Value: 233 (0x000000e9)

KEYCODE_TV_TERRESTRIAL_ANALOG
public static final int KEYCODE_TV_TERRESTRIAL_ANALOG
Key code constant: Analog Terrestrial key. Switches to analog terrestrial broadcast service. * @apiSince 21

Constant Value: 235 (0x000000eb)

KEYCODE_TV_TERRESTRIAL_DIGITAL
public static final int KEYCODE_TV_TERRESTRIAL_DIGITAL
Key code constant: Digital Terrestrial key. Switches to digital terrestrial broadcast service. * @apiSince 21

Constant Value: 236 (0x000000ec)

KEYCODE_TV_TIMER_PROGRAMMING
public static final int KEYCODE_TV_TIMER_PROGRAMMING
Key code constant: Timer programming key. Goes to the timer recording menu. Corresponds to Timer Programming (0x54) of CEC User Control Code. * @apiSince 21

Constant Value: 258 (0x00000102)

KEYCODE_TV_ZOOM_MODE
public static final int KEYCODE_TV_ZOOM_MODE
Key code constant: Zoom mode key. Changes Zoom mode (Normal, Full, Zoom, Wide-zoom, etc.) * @apiSince 21

Constant Value: 255 (0x000000ff)

KEYCODE_U
Added in API level 1
public static final int KEYCODE_U
Key code constant: 'U' key.

Constant Value: 49 (0x00000031)

KEYCODE_UNKNOWN
Added in API level 1
public static final int KEYCODE_UNKNOWN
Key code constant: Unknown key code.

Constant Value: 0 (0x00000000)

KEYCODE_V
Added in API level 1
public static final int KEYCODE_V
Key code constant: 'V' key.

Constant Value: 50 (0x00000032)

KEYCODE_VOICE_ASSIST
public static final int KEYCODE_VOICE_ASSIST
Key code constant: Voice Assist key. Launches the global voice assist activity. Not delivered to applications. * @apiSince 21

Constant Value: 231 (0x000000e7)

KEYCODE_VOLUME_DOWN
public static final int KEYCODE_VOLUME_DOWN
Key code constant: Volume Down key. Adjusts the speaker volume down. * @apiSince 1

Constant Value: 25 (0x00000019)

KEYCODE_VOLUME_MUTE
public static final int KEYCODE_VOLUME_MUTE
Key code constant: Volume Mute key. Mutes the speaker, unlike KEYCODE_MUTE. This key should normally be implemented as a toggle such that the first press mutes the speaker and the second press restores the original volume. * @apiSince 11

Constant Value: 164 (0x000000a4)

KEYCODE_VOLUME_UP
public static final int KEYCODE_VOLUME_UP
Key code constant: Volume Up key. Adjusts the speaker volume up. * @apiSince 1

Constant Value: 24 (0x00000018)

KEYCODE_W
Added in API level 1
public static final int KEYCODE_W
Key code constant: 'W' key.

Constant Value: 51 (0x00000033)

KEYCODE_WAKEUP
public static final int KEYCODE_WAKEUP
Key code constant: Wakeup key. Wakes up the device. Behaves somewhat like KEYCODE_POWER but it has no effect if the device is already awake. * @apiSince 20

Constant Value: 224 (0x000000e0)

KEYCODE_WINDOW
public static final int KEYCODE_WINDOW
Key code constant: Window key. On TV remotes, toggles picture-in-picture mode or other windowing functions. On Android Wear devices, triggers a display offset. * @apiSince 11

Constant Value: 171 (0x000000ab)

KEYCODE_X
Added in API level 1
public static final int KEYCODE_X
Key code constant: 'X' key.

Constant Value: 52 (0x00000034)

KEYCODE_Y
Added in API level 1
public static final int KEYCODE_Y
Key code constant: 'Y' key.

Constant Value: 53 (0x00000035)

KEYCODE_YEN
Added in API level 16
public static final int KEYCODE_YEN
Key code constant: Japanese Yen key.

Constant Value: 216 (0x000000d8)

KEYCODE_Z
Added in API level 1
public static final int KEYCODE_Z
Key code constant: 'Z' key.

Constant Value: 54 (0x00000036)

KEYCODE_ZENKAKU_HANKAKU
Added in API level 16
public static final int KEYCODE_ZENKAKU_HANKAKU
Key code constant: Japanese full-width / half-width key.

Constant Value: 211 (0x000000d3)

KEYCODE_ZOOM_IN
Added in API level 11
public static final int KEYCODE_ZOOM_IN
Key code constant: Zoom in key.

Constant Value: 168 (0x000000a8)

KEYCODE_ZOOM_OUT
Added in API level 11
public static final int KEYCODE_ZOOM_OUT
Key code constant: Zoom out key.

Constant Value: 169 (0x000000a9)

MAX_KEYCODE
Added in API level 1
Deprecated in API level 15
public static final int MAX_KEYCODE
This constant was deprecated in API level 15.
There are now more than MAX_KEYCODE keycodes. Use getMaxKeyCode() instead.

Constant Value: 84 (0x00000054)

META_ALT_LEFT_ON
Added in API level 1
public static final int META_ALT_LEFT_ON
This mask is used to check whether the left ALT meta key is pressed.

See also:

isAltPressed()
getMetaState()
KEYCODE_ALT_LEFT
Constant Value: 16 (0x00000010)

META_ALT_MASK
Added in API level 11
public static final int META_ALT_MASK
This mask is a combination of META_ALT_ON, META_ALT_LEFT_ON and META_ALT_RIGHT_ON.

Constant Value: 50 (0x00000032)

META_ALT_ON
Added in API level 1
public static final int META_ALT_ON
This mask is used to check whether one of the ALT meta keys is pressed.

See also:

isAltPressed()
getMetaState()
KEYCODE_ALT_LEFT
KEYCODE_ALT_RIGHT
Constant Value: 2 (0x00000002)

META_ALT_RIGHT_ON
Added in API level 1
public static final int META_ALT_RIGHT_ON
This mask is used to check whether the right the ALT meta key is pressed.

See also:

isAltPressed()
getMetaState()
KEYCODE_ALT_RIGHT
Constant Value: 32 (0x00000020)

META_CAPS_LOCK_ON
Added in API level 11
public static final int META_CAPS_LOCK_ON
This mask is used to check whether the CAPS LOCK meta key is on.

See also:

isCapsLockOn()
getMetaState()
KEYCODE_CAPS_LOCK
Constant Value: 1048576 (0x00100000)

META_CTRL_LEFT_ON
Added in API level 11
public static final int META_CTRL_LEFT_ON
This mask is used to check whether the left CTRL meta key is pressed.

See also:

isCtrlPressed()
getMetaState()
KEYCODE_CTRL_LEFT
Constant Value: 8192 (0x00002000)

META_CTRL_MASK
Added in API level 11
public static final int META_CTRL_MASK
This mask is a combination of META_CTRL_ON, META_CTRL_LEFT_ON and META_CTRL_RIGHT_ON.

Constant Value: 28672 (0x00007000)

META_CTRL_ON
Added in API level 11
public static final int META_CTRL_ON
This mask is used to check whether one of the CTRL meta keys is pressed.

See also:

isCtrlPressed()
getMetaState()
KEYCODE_CTRL_LEFT
KEYCODE_CTRL_RIGHT
Constant Value: 4096 (0x00001000)

META_CTRL_RIGHT_ON
Added in API level 11
public static final int META_CTRL_RIGHT_ON
This mask is used to check whether the right CTRL meta key is pressed.

See also:

isCtrlPressed()
getMetaState()
KEYCODE_CTRL_RIGHT
Constant Value: 16384 (0x00004000)

META_FUNCTION_ON
Added in API level 11
public static final int META_FUNCTION_ON
This mask is used to check whether the FUNCTION meta key is pressed.

See also:

isFunctionPressed()
getMetaState()
Constant Value: 8 (0x00000008)

META_META_LEFT_ON
Added in API level 11
public static final int META_META_LEFT_ON
This mask is used to check whether the left META meta key is pressed.

See also:

isMetaPressed()
getMetaState()
KEYCODE_META_LEFT
Constant Value: 131072 (0x00020000)

META_META_MASK
Added in API level 11
public static final int META_META_MASK
This mask is a combination of META_META_ON, META_META_LEFT_ON and META_META_RIGHT_ON.

Constant Value: 458752 (0x00070000)

META_META_ON
Added in API level 11
public static final int META_META_ON
This mask is used to check whether one of the META meta keys is pressed.

See also:

isMetaPressed()
getMetaState()
KEYCODE_META_LEFT
KEYCODE_META_RIGHT
Constant Value: 65536 (0x00010000)

META_META_RIGHT_ON
Added in API level 11
public static final int META_META_RIGHT_ON
This mask is used to check whether the right META meta key is pressed.

See also:

isMetaPressed()
getMetaState()
KEYCODE_META_RIGHT
Constant Value: 262144 (0x00040000)

META_NUM_LOCK_ON
Added in API level 11
public static final int META_NUM_LOCK_ON
This mask is used to check whether the NUM LOCK meta key is on.

See also:

isNumLockOn()
getMetaState()
KEYCODE_NUM_LOCK
Constant Value: 2097152 (0x00200000)

META_SCROLL_LOCK_ON
Added in API level 11
public static final int META_SCROLL_LOCK_ON
This mask is used to check whether the SCROLL LOCK meta key is on.

See also:

isScrollLockOn()
getMetaState()
KEYCODE_SCROLL_LOCK
Constant Value: 4194304 (0x00400000)

META_SHIFT_LEFT_ON
Added in API level 1
public static final int META_SHIFT_LEFT_ON
This mask is used to check whether the left SHIFT meta key is pressed.

See also:

isShiftPressed()
getMetaState()
KEYCODE_SHIFT_LEFT
Constant Value: 64 (0x00000040)

META_SHIFT_MASK
Added in API level 11
public static final int META_SHIFT_MASK
This mask is a combination of META_SHIFT_ON, META_SHIFT_LEFT_ON and META_SHIFT_RIGHT_ON.

Constant Value: 193 (0x000000c1)

META_SHIFT_ON
Added in API level 1
public static final int META_SHIFT_ON
This mask is used to check whether one of the SHIFT meta keys is pressed.

See also:

isShiftPressed()
getMetaState()
KEYCODE_SHIFT_LEFT
KEYCODE_SHIFT_RIGHT
Constant Value: 1 (0x00000001)

META_SHIFT_RIGHT_ON
Added in API level 1
public static final int META_SHIFT_RIGHT_ON
This mask is used to check whether the right SHIFT meta key is pressed.

See also:

isShiftPressed()
getMetaState()
KEYCODE_SHIFT_RIGHT
Constant Value: 128 (0x00000080)

META_SYM_ON
Added in API level 1
public static final int META_SYM_ON
This mask is used to check whether the SYM meta key is pressed.

See also:

isSymPressed()
getMetaState()
Constant Value: 4 (0x00000004)

Fields
CREATOR
Added in API level 1
public static final Creator CREATOR
Public constructors
KeyEvent
Added in API level 1
public KeyEvent (int action,
int code)
Create a new key event.

Parameters
action int: Action code: either ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
code int: The key code.
KeyEvent
Added in API level 1
public KeyEvent (long downTime,
long eventTime,
int action,
int code,
int repeat)
Create a new key event.

Parameters
downTime long: The time (in SystemClock.uptimeMillis()) at which this key code originally went down.
eventTime long: The time (in SystemClock.uptimeMillis()) at which this event happened.
action int: Action code: either ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
code int: The key code.
repeat int: A repeat count for down events (> 0 if this is after the initial down) or event count for multiple events.
KeyEvent
Added in API level 1
public KeyEvent (long downTime,
long eventTime,
int action,
int code,
int repeat,
int metaState)
Create a new key event.

Parameters
downTime long: The time (in SystemClock.uptimeMillis()) at which this key code originally went down.
eventTime long: The time (in SystemClock.uptimeMillis()) at which this event happened.
action int: Action code: either ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
code int: The key code.
repeat int: A repeat count for down events (> 0 if this is after the initial down) or event count for multiple events.
metaState int: Flags indicating which meta keys are currently pressed.
KeyEvent
Added in API level 1
public KeyEvent (long downTime,
long eventTime,
int action,
int code,
int repeat,
int metaState,
int deviceId,
int scancode)
Create a new key event.

Parameters
downTime long: The time (in SystemClock.uptimeMillis()) at which this key code originally went down.
eventTime long: The time (in SystemClock.uptimeMillis()) at which this event happened.
action int: Action code: either ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
code int: The key code.
repeat int: A repeat count for down events (> 0 if this is after the initial down) or event count for multiple events.
metaState int: Flags indicating which meta keys are currently pressed.
deviceId int: The device ID that generated the key event.
scancode int: Raw device scan code of the event.
KeyEvent
Added in API level 1
public KeyEvent (long downTime,
long eventTime,
int action,
int code,
int repeat,
int metaState,
int deviceId,
int scancode,
int flags)
Create a new key event.

Parameters
downTime long: The time (in SystemClock.uptimeMillis()) at which this key code originally went down.
eventTime long: The time (in SystemClock.uptimeMillis()) at which this event happened.
action int: Action code: either ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
code int: The key code.
repeat int: A repeat count for down events (> 0 if this is after the initial down) or event count for multiple events.
metaState int: Flags indicating which meta keys are currently pressed.
deviceId int: The device ID that generated the key event.
scancode int: Raw device scan code of the event.
flags int: The flags for this key event
KeyEvent
Added in API level 9
public KeyEvent (long downTime,
long eventTime,
int action,
int code,
int repeat,
int metaState,
int deviceId,
int scancode,
int flags,
int source)
Create a new key event.

Parameters
downTime long: The time (in SystemClock.uptimeMillis()) at which this key code originally went down.
eventTime long: The time (in SystemClock.uptimeMillis()) at which this event happened.
action int: Action code: either ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
code int: The key code.
repeat int: A repeat count for down events (> 0 if this is after the initial down) or event count for multiple events.
metaState int: Flags indicating which meta keys are currently pressed.
deviceId int: The device ID that generated the key event.
scancode int: Raw device scan code of the event.
flags int: The flags for this key event
source int: The input source such as InputDevice#SOURCE_KEYBOARD.
KeyEvent
Added in API level 3
public KeyEvent (long time,
String characters,
int deviceId,
int flags)
Create a new key event for a string of characters. The key code, action, repeat count and source will automatically be set to KEYCODE_UNKNOWN, ACTION_MULTIPLE, 0, and InputDevice#SOURCE_KEYBOARD for you.

Parameters
time long: The time (in SystemClock.uptimeMillis()) at which this event occured.
characters String: The string of characters.
deviceId int: The device ID that generated the key event.
flags int: The flags for this key event
KeyEvent
Added in API level 3
public KeyEvent (KeyEvent origEvent)
Make an exact copy of an existing key event.

Parameters
origEvent KeyEvent
KeyEvent
Added in API level 1
public KeyEvent (KeyEvent origEvent,
long eventTime,
int newRepeat)
This constructor is deprecated.
Use changeTimeRepeat(android.view.KeyEvent, long, int) instead.

Copy an existing key event, modifying its time and repeat count.

Parameters
origEvent KeyEvent: The existing event to be copied.
eventTime long: The new event time (in SystemClock.uptimeMillis()) of the event.
newRepeat int: The new repeat count of the event.
Public methods
changeAction
Added in API level 3
public static KeyEvent changeAction (KeyEvent event,
int action)
Create a new key event that is the same as the given one, but whose action is replaced with the given value.

Parameters
event KeyEvent: The existing event to be copied. This is not modified.
action int: The new action code of the event.
Returns
KeyEvent
changeFlags
Added in API level 3
public static KeyEvent changeFlags (KeyEvent event,
int flags)
Create a new key event that is the same as the given one, but whose flags are replaced with the given value.

Parameters
event KeyEvent: The existing event to be copied. This is not modified.
flags int: The new flags constant.
Returns
KeyEvent
changeTimeRepeat
Added in API level 5
public static KeyEvent changeTimeRepeat (KeyEvent event,
long eventTime,
int newRepeat,
int newFlags)
Create a new key event that is the same as the given one, but whose event time and repeat count are replaced with the given value.

Parameters
event KeyEvent: The existing event to be copied. This is not modified.
eventTime long: The new event time (in SystemClock.uptimeMillis()) of the event.
newRepeat int: The new repeat count of the event.
newFlags int: New flags for the event, replacing the entire value in the original event.
Returns
KeyEvent
changeTimeRepeat
Added in API level 3
public static KeyEvent changeTimeRepeat (KeyEvent event,
long eventTime,
int newRepeat)
Create a new key event that is the same as the given one, but whose event time and repeat count are replaced with the given value.

Parameters
event KeyEvent: The existing event to be copied. This is not modified.
eventTime long: The new event time (in SystemClock.uptimeMillis()) of the event.
newRepeat int: The new repeat count of the event.
Returns
KeyEvent
dispatch
Added in API level 5
public final boolean dispatch (KeyEvent.Callback receiver,
KeyEvent.DispatcherState state,
Object target)
Deliver this key event to a Callback interface. If this is an ACTION_MULTIPLE event and it is not handled, then an attempt will be made to deliver a single normal event.

Parameters
receiver KeyEvent.Callback: The Callback that will be given the event.
state KeyEvent.DispatcherState: State information retained across events.
target Object: The target of the dispatch, for use in tracking.
Returns
boolean The return value from the Callback method that was called.
dispatch
Added in API level 1
Deprecated in API level 15
public final boolean dispatch (KeyEvent.Callback receiver)
This method was deprecated in API level 15.
Use dispatch(android.view.KeyEvent.Callback, android.view.KeyEvent.DispatcherState, java.lang.Object) instead.

Parameters
receiver KeyEvent.Callback
Returns
boolean
getAction
Added in API level 1
public final int getAction ()
Retrieve the action of this key event. May be either ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.

Returns
int The event action: ACTION_DOWN, ACTION_UP, or ACTION_MULTIPLE.
getCharacters
Added in API level 3
Deprecated in API level 29
public final String getCharacters ()
This method was deprecated in API level 29.
no longer used by the input system.

For the special case of a ACTION_MULTIPLE event with key code of KEYCODE_UNKNOWN, this is a raw string of characters associated with the event. In all other cases it is null.

Returns
String Returns a String of 1 or more characters associated with the event.
getDeadChar
Added in API level 1
public static int getDeadChar (int accent,
int c)
Get the character that is produced by putting accent on the character c. For example, getDeadChar('`', 'e') returns è.

Parameters
accent int
c int
Returns
int
getDeviceId
Added in API level 1
public final int getDeviceId ()
Gets the id for the device that this event came from. An id of zero indicates that the event didn't come from a physical device and maps to the default keymap. The other numbers are arbitrary and you shouldn't depend on the values.

Returns
int The device id.
getDisplayLabel
Added in API level 1
public char getDisplayLabel ()
Gets the primary character for this key. In other words, the label that is physically printed on it.

Returns
char The display label character, or 0 if none (eg. for non-printing keys).
getDownTime
Added in API level 1
public final long getDownTime ()
Retrieve the time of the most recent key down event, in the SystemClock.uptimeMillis() time base. If this is a down event, this will be the same as getEventTime(). Note that when chording keys, this value is the down time of the most recently pressed key, which may not be the same physical key of this event.

Returns
long Returns the most recent key down time, in the SystemClock.uptimeMillis() time base
getEventTime
Added in API level 1
public final long getEventTime ()
Retrieve the time this event occurred, in the SystemClock.uptimeMillis() time base.

Returns
long Returns the time this event occurred, in the SystemClock.uptimeMillis() time base.
getFlags
Added in API level 1
public final int getFlags ()
Returns the flags for this key event.

Returns
int
See also:

FLAG_WOKE_HERE
getKeyCharacterMap
Added in API level 11
public final KeyCharacterMap getKeyCharacterMap ()
Gets the KeyCharacterMap associated with the keyboard device.

Returns
KeyCharacterMap The associated key character map.
Throws
android.view.KeyCharacterMap.UnavailableException KeyCharacterMap.UnavailableException} if the key character map could not be loaded because it was malformed or the default key character map is missing from the system.
See also:

KeyCharacterMap.load(int)
getKeyCode
Added in API level 1
public final int getKeyCode ()
Retrieve the key code of the key event. This is the physical key that was pressed, not the Unicode character.

Returns
int The key code of the event.
getKeyData
Added in API level 1
Deprecated in API level 15
public boolean getKeyData (KeyCharacterMap.KeyData results)
This method was deprecated in API level 15.
instead use getDisplayLabel(), getNumber() or getUnicodeChar(int).

Get the character conversion data for a given key code.

Parameters
results KeyCharacterMap.KeyData: A KeyCharacterMap.KeyData instance that will be filled with the results.
Returns
boolean True if the key was mapped. If the key was not mapped, results is not modified.
getMatch
Added in API level 1
public char getMatch (char[] chars,
int metaState)
Gets the first character in the character array that can be generated by the specified key code. If there are multiple choices, prefers the one that would be generated with the specified meta key modifier state.

Parameters
chars char: The array of matching characters to consider.
metaState int: The preferred meta key modifier state.
Returns
char The matching associated character, or 0 if none.
getMatch
Added in API level 1
public char getMatch (char[] chars)
Gets the first character in the character array that can be generated by the specified key code.

This is a convenience function that returns the same value as getMatch(chars, 0).

Parameters
chars char: The array of matching characters to consider.
Returns
char The matching associated character, or 0 if none.
getMaxKeyCode
Added in API level 3
public static int getMaxKeyCode ()
Returns the maximum keycode.

Returns
int
getMetaState
Added in API level 1
public final int getMetaState ()
Returns the state of the meta keys.

Returns
int an integer in which each bit set to 1 represents a pressed meta key
See also:

isAltPressed()
isShiftPressed()
isSymPressed()
isCtrlPressed()
isMetaPressed()
isFunctionPressed()
isCapsLockOn()
isNumLockOn()
isScrollLockOn()
META_ALT_ON
META_ALT_LEFT_ON
META_ALT_RIGHT_ON
META_SHIFT_ON
META_SHIFT_LEFT_ON
META_SHIFT_RIGHT_ON
META_SYM_ON
META_FUNCTION_ON
META_CTRL_ON
META_CTRL_LEFT_ON
META_CTRL_RIGHT_ON
META_META_ON
META_META_LEFT_ON
META_META_RIGHT_ON
META_CAPS_LOCK_ON
META_NUM_LOCK_ON
META_SCROLL_LOCK_ON
getModifiers()
getModifierMetaStateMask
Added in API level 11
public static int getModifierMetaStateMask ()
Gets a mask that includes all valid modifier key meta state bits.

For the purposes of this function, KEYCODE_CAPS_LOCK, KEYCODE_SCROLL_LOCK, and KEYCODE_NUM_LOCK are not considered modifier keys. Consequently, the mask specifically excludes META_CAPS_LOCK_ON, META_SCROLL_LOCK_ON and META_NUM_LOCK_ON.

Returns
int The modifier meta state mask which is a combination of META_SHIFT_ON, META_SHIFT_LEFT_ON, META_SHIFT_RIGHT_ON, META_ALT_ON, META_ALT_LEFT_ON, META_ALT_RIGHT_ON, META_CTRL_ON, META_CTRL_LEFT_ON, META_CTRL_RIGHT_ON, META_META_ON, META_META_LEFT_ON, META_META_RIGHT_ON, META_SYM_ON, META_FUNCTION_ON.
getModifiers
Added in API level 13
public final int getModifiers ()
Returns the state of the modifier keys.

For the purposes of this function, KEYCODE_CAPS_LOCK, KEYCODE_SCROLL_LOCK, and KEYCODE_NUM_LOCK are not considered modifier keys. Consequently, this function specifically masks out META_CAPS_LOCK_ON, META_SCROLL_LOCK_ON and META_NUM_LOCK_ON.

The value returned consists of the meta state (from getMetaState()) normalized using normalizeMetaState(int) and then masked with getModifierMetaStateMask() so that only valid modifier bits are retained.

Returns
int An integer in which each bit set to 1 represents a pressed modifier key.
See also:

getMetaState()
getNumber
Added in API level 1
public char getNumber ()
Gets the number or symbol associated with the key.

The character value is returned, not the numeric value. If the key is not a number, but is a symbol, the symbol is retuned.

This method is intended to to support dial pads and other numeric or symbolic entry on keyboards where certain keys serve dual function as alphabetic and symbolic keys. This method returns the number or symbol associated with the key independent of whether the user has pressed the required modifier.

For example, on one particular keyboard the keys on the top QWERTY row generate numbers when ALT is pressed such that ALT-Q maps to '1'. So for that keyboard when getNumber() is called with KeyEvent#KEYCODE_Q it returns '1' so that the user can type numbers without pressing ALT when it makes sense.

Returns
char The associated numeric or symbolic character, or 0 if none.
getRepeatCount
Added in API level 1
public final int getRepeatCount ()
Retrieve the repeat count of the event. For key down events, this is the number of times the key has repeated with the first down starting at 0 and counting up from there. For key up events, this is always equal to zero. For multiple key events, this is the number of down/up pairs that have occurred.

Returns
int The number of times the key has repeated.
getScanCode
Added in API level 1
public final int getScanCode ()
Retrieve the hardware key id of this key event. These values are not reliable and vary from device to device.

Mostly this is here for debugging purposes.

Returns
int
getSource
Added in API level 9
public final int getSource ()
Gets the source of the event.

Returns
int The event source or InputDevice#SOURCE_UNKNOWN if unknown.
getUnicodeChar
Added in API level 1
public int getUnicodeChar (int metaState)
Gets the Unicode character generated by the specified key and meta key state combination.

Returns the Unicode character that the specified key would produce when the specified meta bits (see MetaKeyKeyListener) were active.

Returns 0 if the key is not one that is used to type Unicode characters.

If the return value has bit KeyCharacterMap#COMBINING_ACCENT set, the key is a "dead key" that should be combined with another to actually produce a character -- see KeyCharacterMap#getDeadChar -- after masking with KeyCharacterMap#COMBINING_ACCENT_MASK.

Parameters
metaState int: The meta key modifier state.
Returns
int The associated character or combining accent, or 0 if none.
getUnicodeChar
Added in API level 1
public int getUnicodeChar ()
Gets the Unicode character generated by the specified key and meta key state combination.

Returns the Unicode character that the specified key would produce when the specified meta bits (see MetaKeyKeyListener) were active.

Returns 0 if the key is not one that is used to type Unicode characters.

If the return value has bit KeyCharacterMap#COMBINING_ACCENT set, the key is a "dead key" that should be combined with another to actually produce a character -- see KeyCharacterMap#getDeadChar -- after masking with KeyCharacterMap#COMBINING_ACCENT_MASK.

Returns
int The associated character or combining accent, or 0 if none.
hasModifiers
Added in API level 11
public final boolean hasModifiers (int modifiers)
Returns true if only the specified modifiers keys are pressed. Returns false if a different combination of modifier keys are pressed.

For the purposes of this function, KEYCODE_CAPS_LOCK, KEYCODE_SCROLL_LOCK, and KEYCODE_NUM_LOCK are not considered modifier keys. Consequently, this function ignores META_CAPS_LOCK_ON, META_SCROLL_LOCK_ON and META_NUM_LOCK_ON.

If the specified modifier mask includes directional modifiers, such as META_SHIFT_LEFT_ON, then this method ensures that the modifier is pressed on that side. If the specified modifier mask includes non-directional modifiers, such as META_SHIFT_ON, then this method ensures that the modifier is pressed on either side. If the specified modifier mask includes both directional and non-directional modifiers for the same type of key, such as META_SHIFT_ON and META_SHIFT_LEFT_ON, then this method throws an illegal argument exception.

Parameters
modifiers int: The meta state of the modifier keys to check. May be a combination of modifier meta states as defined by getModifierMetaStateMask(). May be 0 to ensure that no modifier keys are pressed.
Returns
boolean True if only the specified modifier keys are pressed.
Throws
IllegalArgumentException if the modifiers parameter contains invalid modifiers
See also:

metaStateHasModifiers(int, int)
hasNoModifiers
Added in API level 11
public final boolean hasNoModifiers ()
Returns true if no modifier keys are pressed.

For the purposes of this function, KEYCODE_CAPS_LOCK, KEYCODE_SCROLL_LOCK, and KEYCODE_NUM_LOCK are not considered modifier keys. Consequently, this function ignores META_CAPS_LOCK_ON, META_SCROLL_LOCK_ON and META_NUM_LOCK_ON.

The meta state is normalized prior to comparison using normalizeMetaState(int).

Returns
boolean True if no modifier keys are pressed.
See also:

metaStateHasNoModifiers(int)
isAltPressed
Added in API level 1
public final boolean isAltPressed ()
Returns the pressed state of the ALT meta key.

Returns
boolean true if the ALT key is pressed, false otherwise
See also:

KEYCODE_ALT_LEFT
KEYCODE_ALT_RIGHT
META_ALT_ON
isCanceled
Added in API level 5
public final boolean isCanceled ()
For ACTION_UP events, indicates that the event has been canceled as per FLAG_CANCELED.

Returns
boolean
isCapsLockOn
Added in API level 11
public final boolean isCapsLockOn ()
Returns the locked state of the CAPS LOCK meta key.

Returns
boolean true if the CAPS LOCK key is on, false otherwise
See also:

KEYCODE_CAPS_LOCK
META_CAPS_LOCK_ON
isCtrlPressed
Added in API level 11
public final boolean isCtrlPressed ()
Returns the pressed state of the CTRL meta key.

Returns
boolean true if the CTRL key is pressed, false otherwise
See also:

KEYCODE_CTRL_LEFT
KEYCODE_CTRL_RIGHT
META_CTRL_ON
isFunctionPressed
Added in API level 11
public final boolean isFunctionPressed ()
Returns the pressed state of the FUNCTION meta key.

Returns
boolean true if the FUNCTION key is pressed, false otherwise
See also:

KEYCODE_FUNCTION
META_FUNCTION_ON
isGamepadButton
Added in API level 12
public static final boolean isGamepadButton (int keyCode)
Returns true if the specified keycode is a gamepad button.

Parameters
keyCode int
Returns
boolean True if the keycode is a gamepad button, such as KEYCODE_BUTTON_A.
isLongPress
Added in API level 5
public final boolean isLongPress ()
For ACTION_DOWN events, indicates that the event has been canceled as per FLAG_LONG_PRESS.

Returns
boolean
isMetaPressed
Added in API level 11
public final boolean isMetaPressed ()
Returns the pressed state of the META meta key.

Returns
boolean true if the META key is pressed, false otherwise
See also:

KEYCODE_META_LEFT
KEYCODE_META_RIGHT
META_META_ON
isModifierKey
Added in API level 1
public static boolean isModifierKey (int keyCode)
Returns true if this key code is a modifier key.

For the purposes of this function, KEYCODE_CAPS_LOCK, KEYCODE_SCROLL_LOCK, and KEYCODE_NUM_LOCK are not considered modifier keys. Consequently, this function return false for those keys.

Parameters
keyCode int
Returns
boolean True if the key code is one of KEYCODE_SHIFT_LEFT KEYCODE_SHIFT_RIGHT, KEYCODE_ALT_LEFT, KEYCODE_ALT_RIGHT, KEYCODE_CTRL_LEFT, KEYCODE_CTRL_RIGHT, KEYCODE_META_LEFT, or KEYCODE_META_RIGHT, KEYCODE_SYM, KEYCODE_NUM, KEYCODE_FUNCTION.
isNumLockOn
Added in API level 11
public final boolean isNumLockOn ()
Returns the locked state of the NUM LOCK meta key.

Returns
boolean true if the NUM LOCK key is on, false otherwise
See also:

KEYCODE_NUM_LOCK
META_NUM_LOCK_ON
isPrintingKey
Added in API level 1
public boolean isPrintingKey ()
Returns true if this key produces a glyph.

Returns
boolean True if the key is a printing key.
isScrollLockOn
Added in API level 11
public final boolean isScrollLockOn ()
Returns the locked state of the SCROLL LOCK meta key.

Returns
boolean true if the SCROLL LOCK key is on, false otherwise
See also:

KEYCODE_SCROLL_LOCK
META_SCROLL_LOCK_ON
isShiftPressed
Added in API level 1
public final boolean isShiftPressed ()
Returns the pressed state of the SHIFT meta key.

Returns
boolean true if the SHIFT key is pressed, false otherwise
See also:

KEYCODE_SHIFT_LEFT
KEYCODE_SHIFT_RIGHT
META_SHIFT_ON
isSymPressed
Added in API level 1
public final boolean isSymPressed ()
Returns the pressed state of the SYM meta key.

Returns
boolean true if the SYM key is pressed, false otherwise
See also:

KEYCODE_SYM
META_SYM_ON
isSystem
Added in API level 1
public final boolean isSystem ()
Is this a system key? System keys can not be used for menu shortcuts.

Returns
boolean
isTracking
Added in API level 5
public final boolean isTracking ()
For ACTION_UP events, indicates that the event is still being tracked from its initial down event as per FLAG_TRACKING.

Returns
boolean
keyCodeFromString
Added in API level 12
public static int keyCodeFromString (String symbolicName)
Gets a keycode by its symbolic name such as "KEYCODE_A" or an equivalent numeric constant such as "29". For symbolic names, starting in Build.VERSIONCODES.Q the prefix "KEYCODE" is optional.

Parameters
symbolicName String: The symbolic name of the keycode. This value must never be null.
Returns
int The keycode or KEYCODE_UNKNOWN if not found.
See also:

keyCodeToString(int)
keyCodeToString
Added in API level 12
public static String keyCodeToString (int keyCode)
Returns a string that represents the symbolic name of the specified keycode such as "KEYCODE_A", "KEYCODE_DPAD_UP", or an equivalent numeric constant such as "1001" if unknown. This function is intended to be used mostly for debugging, logging, and testing. It is not locale-specific and is not intended to be used in a user-facing manner.

Parameters
keyCode int: The key code.
Returns
String The symbolic name of the specified keycode.
See also:

KeyCharacterMap.getDisplayLabel(int)
metaStateHasModifiers
Added in API level 11
public static boolean metaStateHasModifiers (int metaState,
int modifiers)
Returns true if only the specified modifier keys are pressed according to the specified meta state. Returns false if a different combination of modifier keys are pressed.

For the purposes of this function, KEYCODE_CAPS_LOCK, KEYCODE_SCROLL_LOCK, and KEYCODE_NUM_LOCK are not considered modifier keys. Consequently, this function ignores META_CAPS_LOCK_ON, META_SCROLL_LOCK_ON and META_NUM_LOCK_ON.

If the specified modifier mask includes directional modifiers, such as META_SHIFT_LEFT_ON, then this method ensures that the modifier is pressed on that side. If the specified modifier mask includes non-directional modifiers, such as META_SHIFT_ON, then this method ensures that the modifier is pressed on either side. If the specified modifier mask includes both directional and non-directional modifiers for the same type of key, such as META_SHIFT_ON and META_SHIFT_LEFT_ON, then this method throws an illegal argument exception.

Parameters
metaState int: The meta state to consider.
modifiers int: The meta state of the modifier keys to check. May be a combination of modifier meta states as defined by getModifierMetaStateMask(). May be 0 to ensure that no modifier keys are pressed.
Returns
boolean True if only the specified modifier keys are pressed.
Throws
IllegalArgumentException if the modifiers parameter contains invalid modifiers
See also:

hasModifiers(int)
metaStateHasNoModifiers
Added in API level 11
public static boolean metaStateHasNoModifiers (int metaState)
Returns true if no modifiers keys are pressed according to the specified meta state.

For the purposes of this function, KEYCODE_CAPS_LOCK, KEYCODE_SCROLL_LOCK, and KEYCODE_NUM_LOCK are not considered modifier keys. Consequently, this function ignores META_CAPS_LOCK_ON, META_SCROLL_LOCK_ON and META_NUM_LOCK_ON.

The meta state is normalized prior to comparison using normalizeMetaState(int).

Parameters
metaState int: The meta state to consider.
Returns
boolean True if no modifier keys are pressed.
See also:

hasNoModifiers()
normalizeMetaState
Added in API level 11
public static int normalizeMetaState (int metaState)
Normalizes the specified meta state.

The meta state is normalized such that if either the left or right modifier meta state bits are set then the result will also include the universal bit for that modifier.

If the specified meta state contains META_ALT_LEFT_ON then the result will also contain META_ALT_ON in addition to META_ALT_LEFT_ON and the other bits that were specified in the input. The same is process is performed for shift, control and meta.

If the specified meta state contains synthetic meta states defined by MetaKeyKeyListener, then those states are translated here and the original synthetic meta states are removed from the result. MetaKeyKeyListener#META_CAP_LOCKED is translated to META_CAPS_LOCK_ON. MetaKeyKeyListener#META_ALT_LOCKED is translated to META_ALT_ON. MetaKeyKeyListener#META_SYM_LOCKED is translated to META_SYM_ON.

Undefined meta state bits are removed.

Parameters
metaState int: The meta state.
Returns
int The normalized meta state.
setSource
Added in API level 12
public final void setSource (int source)
Parameters
source int
startTracking
Added in API level 5
public final void startTracking ()
Call this during Callback#onKeyDown to have the system track the key through its final up (possibly including a long press). Note that only one key can be tracked at a time -- if another key down event is received while a previous one is being tracked, tracking is stopped on the previous event.

toString
Added in API level 1
public String toString ()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Returns
String a string representation of the object.
writeToParcel
Added in API level 1
public void writeToParcel (Parcel out,
int flags)
Flatten this object in to a Parcel.

Parameters
out Parcel: The Parcel in which the object should be written.
flags int: Additional flags about how the object should be written. May be 0 or Parcelable.PARCELABLE_WRITE_RETURN_VALUE. Value is either 0 or a combination of Parcelable.PARCELABLE_WRITE_RETURN_VALUE, and android.os.Parcelable.PARCELABLE_ELIDE_DUPLICATES

原文UiSelector, 由于谷歌说这个已经弃用了,吓得我赶快Copy下来.
新文档: UiSelector
经过对比呢, 这两个文档截止今天(2020-3-9)一模一样, 虚惊一场

UiSelector

This package is part of the Android support library which is no longer maintained. The support library has been superseded by AndroidX which is part of Jetpack. We recommend using the AndroidX libraries in all new projects. You should also consider migrating existing projects to AndroidX.

public class UiSelector
extends Object
java.lang.Object
   ↳    android.support.test.uiautomator.UiSelector

Specifies the elements in the layout hierarchy for tests to target, filtered by properties such as text value, content-description, class name, and state information. You can also target an element by its location in a layout hierarchy.

Summary

Public constructors

UiSelector()

Public methods

UiSelector checkable(boolean val)
Set the search criteria to match widgets that are checkable.

UiSelector checked(boolean val)
Set the search criteria to match widgets that are currently checked (usually for checkboxes).

UiSelector childSelector(UiSelector selector)
Adds a child UiSelector criteria to this selector.

UiSelector className(String className)
Set the search criteria to match the class property for a widget (for example, "android.widget.Button").

UiSelector `className(Class type)` Set the search criteria to match the class property for a widget (for example, "android.widget.Button").

UiSelector classNameMatches(String regex)
Set the search criteria to match the class property for a widget, using a regular expression.

UiSelector clickable(boolean val)
Set the search criteria to match widgets that are clickable.

UiSelector description(String desc)
Set the search criteria to match the content-description property for a widget.

UiSelector descriptionContains(String desc)
Set the search criteria to match the content-description property for a widget.

UiSelector descriptionMatches(String regex)
Set the search criteria to match the content-description property for a widget.

UiSelector descriptionStartsWith(String desc)
Set the search criteria to match the content-description property for a widget.

UiSelector enabled(boolean val)
Set the search criteria to match widgets that are enabled.

UiSelector focusable(boolean val)
Set the search criteria to match widgets that are focusable.

UiSelector focused(boolean val)
Set the search criteria to match widgets that have focus.

UiSelector fromParent(UiSelector selector)
Adds a child UiSelector criteria to this selector which is used to start search from the parent widget.

UiSelector index(int index)
Set the search criteria to match the widget by its node index in the layout hierarchy.

UiSelector instance(int instance)
Set the search criteria to match the widget by its instance number.

UiSelector longClickable(boolean val)
Set the search criteria to match widgets that are long-clickable.

UiSelector packageName(String name)
Set the search criteria to match the package name of the application that contains the widget.

UiSelector packageNameMatches(String regex)
Set the search criteria to match the package name of the application that contains the widget.

UiSelector resourceId(String id)
Set the search criteria to match the given resource ID.

UiSelector resourceIdMatches(String regex)
Set the search criteria to match the resource ID of the widget, using a regular expression.

UiSelector scrollable(boolean val)
Set the search criteria to match widgets that are scrollable.

UiSelector selected(boolean val)
Set the search criteria to match widgets that are currently selected.

UiSelector text(String text)
Set the search criteria to match the visible text displayed in a widget (for example, the text label to launch an app).

UiSelector textContains(String text)
Set the search criteria to match the visible text in a widget where the visible text must contain the string in your input argument.

UiSelector textMatches(String regex)
Set the search criteria to match the visible text displayed in a layout element, using a regular expression.

UiSelector textStartsWith(String text)
Set the search criteria to match visible text in a widget that is prefixed by the text parameter.

String toString()

Protected methods

UiSelector cloneSelector()

Inherited methods

From class java.lang.Object

Object  clone()
boolean equals(Object arg0)
void    finalize()
final Class<?>  getClass()
int hashCode()
final void  notify()
final void  notifyAll()
String  toString()
final void  wait(long arg0, int arg1)
final void  wait(long arg0)
final void  wait()

Public constructors

UiSelector
UiSelector ()
Public methods
checkable
UiSelector checkable (boolean val)
Set the search criteria to match widgets that are checkable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.

Parameters
val boolean: Value to match
Returns
UiSelector UiSelector with the specified search criteria
checked
UiSelector checked (boolean val)
Set the search criteria to match widgets that are currently checked (usually for checkboxes). Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.

Parameters
val boolean: Value to match
Returns
UiSelector UiSelector with the specified search criteria
childSelector
UiSelector childSelector (UiSelector selector)
Adds a child UiSelector criteria to this selector. Use this selector to narrow the search scope to child widgets under a specific parent widget.

Returns
UiSelector UiSelector with this added search criterion
className
UiSelector className (String className)
Set the search criteria to match the class property for a widget (for example, "android.widget.Button").

Parameters
className String: Value to match
Returns
UiSelector UiSelector with the specified search criteria
className
UiSelector className (Class type)
Set the search criteria to match the class property for a widget (for example, "android.widget.Button").

Parameters
type Class: type
Returns
UiSelector UiSelector with the specified search criteria
classNameMatches
UiSelector classNameMatches (String regex)
Set the search criteria to match the class property for a widget, using a regular expression.

Parameters
regex String: a regular expression
Returns
UiSelector UiSelector with the specified search criteria
clickable
UiSelector clickable (boolean val)
Set the search criteria to match widgets that are clickable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.

Parameters
val boolean: Value to match
Returns
UiSelector UiSelector with the specified search criteria
description
UiSelector description (String desc)
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must match exactly with the string in your input argument. Matching is case-sensitive.

Parameters
desc String: Value to match
Returns
UiSelector UiSelector with the specified search criteria
descriptionContains
UiSelector descriptionContains (String desc)
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must contain the string in your input argument. Matching is case-insensitive.

Parameters
desc String: Value to match
Returns
UiSelector UiSelector with the specified search criteria
descriptionMatches
UiSelector descriptionMatches (String regex)
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must match exactly with the string in your input argument.

Parameters
regex String: a regular expression
Returns
UiSelector UiSelector with the specified search criteria
descriptionStartsWith
UiSelector descriptionStartsWith (String desc)
Set the search criteria to match the content-description property for a widget. The content-description is typically used by the Android Accessibility framework to provide an audio prompt for the widget when the widget is selected. The content-description for the widget must start with the string in your input argument. Matching is case-insensitive.

Parameters
desc String: Value to match
Returns
UiSelector UiSelector with the specified search criteria
enabled
UiSelector enabled (boolean val)
Set the search criteria to match widgets that are enabled. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.

Parameters
val boolean: Value to match
Returns
UiSelector UiSelector with the specified search criteria
focusable
UiSelector focusable (boolean val)
Set the search criteria to match widgets that are focusable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.

Parameters
val boolean: Value to match
Returns
UiSelector UiSelector with the specified search criteria
focused
UiSelector focused (boolean val)
Set the search criteria to match widgets that have focus. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.

Parameters
val boolean: Value to match
Returns
UiSelector UiSelector with the specified search criteria
fromParent
UiSelector fromParent (UiSelector selector)
Adds a child UiSelector criteria to this selector which is used to start search from the parent widget. Use this selector to narrow the search scope to sibling widgets as well all child widgets under a parent.

Returns
UiSelector UiSelector with this added search criterion
index
UiSelector index (int index)
Set the search criteria to match the widget by its node index in the layout hierarchy. The index value must be 0 or greater. Using the index can be unreliable and should only be used as a last resort for matching. Instead, consider using the instance(int) method.

Parameters
index int: Value to match
Returns
UiSelector UiSelector with the specified search criteria
instance
UiSelector instance (int instance)
Set the search criteria to match the widget by its instance number. The instance value must be 0 or greater, where the first instance is 0. For example, to simulate a user click on the third image that is enabled in a UI screen, you could specify a a search criteria where the instance is 2, the className(String) matches the image widget class, and enabled(boolean) is true. The code would look like this: new UiSelector().className("android.widget.ImageView") .enabled(true).instance(2);

Parameters
instance int: Value to match
Returns
UiSelector UiSelector with the specified search criteria
longClickable
UiSelector longClickable (boolean val)
Set the search criteria to match widgets that are long-clickable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.

Parameters
val boolean: Value to match
Returns
UiSelector UiSelector with the specified search criteria
packageName
UiSelector packageName (String name)
Set the search criteria to match the package name of the application that contains the widget.

Parameters
name String: Value to match
Returns
UiSelector UiSelector with the specified search criteria
packageNameMatches
UiSelector packageNameMatches (String regex)
Set the search criteria to match the package name of the application that contains the widget.

Parameters
regex String: a regular expression
Returns
UiSelector UiSelector with the specified search criteria
resourceId
UiSelector resourceId (String id)
Set the search criteria to match the given resource ID.

Parameters
id String: Value to match
Returns
UiSelector UiSelector with the specified search criteria
resourceIdMatches
UiSelector resourceIdMatches (String regex)
Set the search criteria to match the resource ID of the widget, using a regular expression.

Parameters
regex String: a regular expression
Returns
UiSelector UiSelector with the specified search criteria
scrollable
UiSelector scrollable (boolean val)
Set the search criteria to match widgets that are scrollable. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.

Parameters
val boolean: Value to match
Returns
UiSelector UiSelector with the specified search criteria
selected
UiSelector selected (boolean val)
Set the search criteria to match widgets that are currently selected. Typically, using this search criteria alone is not useful. You should also include additional criteria, such as text, content-description, or the class name for a widget. If no other search criteria is specified, and there is more than one matching widget, the first widget in the tree is selected.

Parameters
val boolean: Value to match
Returns
UiSelector UiSelector with the specified search criteria
text
UiSelector text (String text)
Set the search criteria to match the visible text displayed in a widget (for example, the text label to launch an app). The text for the element must match exactly with the string in your input argument. Matching is case-sensitive.

Parameters
text String: Value to match
Returns
UiSelector UiSelector with the specified search criteria
textContains
UiSelector textContains (String text)
Set the search criteria to match the visible text in a widget where the visible text must contain the string in your input argument. The matching is case-sensitive.

Parameters
text String: Value to match
Returns
UiSelector UiSelector with the specified search criteria
textMatches
UiSelector textMatches (String regex)
Set the search criteria to match the visible text displayed in a layout element, using a regular expression. The text in the widget must match exactly with the string in your input argument.

Parameters
regex String: a regular expression
Returns
UiSelector UiSelector with the specified search criteria
textStartsWith
UiSelector textStartsWith (String text)
Set the search criteria to match visible text in a widget that is prefixed by the text parameter. The matching is case-insensitive.

Parameters
text String: Value to match
Returns
UiSelector UiSelector with the specified search criteria
toString
String toString ()
Returns
String
Protected methods
cloneSelector
UiSelector cloneSelector ()
Returns
UiSelector

Command line tool

版本0.10中的新功能。
Scrapy是通过scrapy命令行工具控制的,在这里称为“ Scrapy工具”,以将其与子命令区分开,我们仅将子命令称为“命令”或“ Scrapy命令”。
Scrapy工具提供了多个命令,用于多种用途,每个命令接受一组不同的参数和选项。
(为了支持独立的scrapyd-deploy,在1.0中已删除scrapy deploy命令。请参阅部署项目。)

配置设置

Scrapy将在标准位置的ini样式scrapy.cfg文件中查找配置参数:

  1. /etc/scrapy.cfgc:\scrapy\scrapy.cfg (系统级),
  2. ~/.config/scrapy.cfg ($XDG_CONFIG_HOME) 以及 ~/.scray.cfg ($HOME) 用来做(用户级)全局设置,
  3. scrapy.cfg 位于Scrapy项目根目录(见下节).

这些文件中的设置将按照列出的优先顺序进行合并:用户定义的值的优先级高于系统级的默认值,并且在定义时,项目级的设置将覆盖所有其他设置。
Scrapy还了解并可以通过许多环境变量进行配置。当前这些是:

Scrapy项目的默认结构

在研究命令行工具及其子命令之前,首先让我们了解Scrapy项目的目录结构。
尽管可以修改,但默认情况下,所有Scrapy项目都具有相同的文件结构,类似于:

scrapy.cfg
myproject/
    __init__.py
    items.py
    middlewares.py
    pipelines.py
    settings.py
    spiders/
        __init__.py
        spider1.py
        spider2.py
        ...

scrapy.cfg文件所在的目录称为项目根目录。该文件包含定义项目设置的python模块的名称。这是一个例子:

[settings]
default = myproject.settings

在项目之间共享根目录

一个项目根目录(包含scrapy.cfg的目录)可以由多个Scrapy项目共享,每个项目都有自己的设置模块。
在这种情况下,必须在scrapy.cfg文件的[settings]下为这些设置模块定义一个或多个别名:

[settings]
default = myproject1.settings
project1 = myproject1.settings
project2 = myproject2.settings

默认情况下,scrapy命令行工具将使用默认设置。使用SCRAPY_PROJECT环境变量来指定其他项目以供scrapy使用:

$ scrapy settings --get BOT_NAME
Project 1 Bot
$ export SCRAPY_PROJECT=project2
$ scrapy settings --get BOT_NAME
Project 2 Bot

使用scrapy工具

您可以先运行不带任何参数的Scrapy工具,它会显示一些用法帮助和可用命令:

Scrapy X.Y - no active project

Usage:
  scrapy <command> [options] [args]

Available commands:
  crawl         Run a spider
  fetch         Fetch a URL using the Scrapy downloader
[...]

如果您在Scrapy项目中,第一行将打印当前活动的项目。在此示例中,它是从项目外部运行的。如果从项目内部运行,它将打印出以下内容:

Scrapy X.Y - project: myproject

Usage:
  scrapy <command> [options] [args]

[...]

创建项目

通常,使用scrapy工具要做的第一件事是创建Scrapy项目:

scrapy startproject myproject [project_dir]

这将在project_dir目录下创建一个Scrapy项目。如果未指定project_dir,则project_dir将与myproject相同。
接下来,进入新项目目录:

cd project_dir

您已经准备好使用scrapy命令管理和控制您的项目。

控制项目

您可以从项目内部使用scrapy工具来控制和管理它们。
例如,创建一个新的蜘蛛:

scrapy genspider mydomain mydomain.com

一些Scrapy命令(例如crawl)必须从Scrapy项目内部运行。请参阅下面的命令参考,以获取有关哪些命令必须在项目内部运行以及哪些不是必须的更多信息。
还请记住,从项目内部运行某些命令时,它们的行为可能略有不同。例如,如果要获取的url与某些特定的爬虫关联,则fetch命令将会覆盖爬虫(例如user_agent属性来覆盖user-agent)。这是有意的,因为fetch命令用于检查爬虫如何下载页面。

可用的工具命令

本节包含可用的内置命令的列表,并带有说明和一些用法示例。请记住,您始终可以通过运行以下命令获取有关每个命令的更多信息:

scrapy <command> -h

您可以使用以下命令查看所有可用命令:

scrapy -h

有两种命令,它们只能在Scrapy项目内部运行(特定于项目的命令),也可以在没有活动的Scrapy项目内部运行(全局命令),尽管它们在项目内部运行时的行为可能略有不同(因为他们会使用项目的覆盖设置)。
全局命令:

  • startproject

  • genspider

  • settings

  • runspider

  • shell

  • fetch

  • view

  • version
    仅项目可用命令:

  • crawl

  • check

  • list

  • edit

  • parse

  • bench

    startproject

  • 语法: scrapy startproject <project_name> [project_dir]

  • 需要项目: 不需要
    project_dir目录下创建一个名为project_name的新Scrapy项目。如果未指定project_dir,则project_dir将与project_name相同。
    用法示例:

    $ scrapy startproject myproject

    genspider

  • 语法: scrapy genspider [-t template] <name> <domain>

  • 需要项目: 不需要
    如果从项目内部调用,则在当前文件夹或当前项目的Spiders文件夹中创建一个新的Spider。<name>参数设置为蜘蛛的名称,而<domain>用于生成允许的域和start_urls蜘蛛的属性。
    用法示例:

    
    $ scrapy genspider -l
    Available templates:
    basic
    crawl
    csvfeed
    xmlfeed

$ scrapy genspider example example.com
Created spider 'example' using template 'basic'

$ scrapy genspider -t crawl scrapyorg scrapy.org
Created spider 'scrapyorg' using template 'crawl'

这只是用于基于预定义模板创建蜘蛛的便利快捷命令,但肯定不是唯一的创建蜘蛛的方法。您可以自己创建蜘蛛源代码文件,而不使用此命令。

###crawl
* 语法: `scrapy crawl <spider>`
* 需要项目: 需要
开始使用蜘蛛抓取。
用法示例:

$ scrapy crawl myspider
[ ... myspider starts crawling ... ]

###check
* 语法: `scrapy check [-l] <spider>
* 需要项目: 需要
运行合法性检查.
用法示例:

$ scrapy check -l
first_spider

  • parse
  • parse_item
    second_spider
  • parse
  • parse_item

$ scrapy check
[FAILED] first_spider:parse_item

'RetailPricex' field is missing

[FAILED] first_spider:parse

Returned 92 requests, expected 0..4

###list
* 语法: `scrapy list`
* 需要项目: 需要
列出当前项目中所有可用的蜘蛛。输出是每行一个蜘蛛。
用法示例:

$ scrapy list
spider1
spider2


###edit
语法: scrapy edit <spider>
* 需要项目: 需要
使用EDITOR环境变量或(如果未设置)EDITOR设置中定义的编辑器来编辑给定的蜘蛛。

在大多数情况下,此命令仅作为便利快捷方式提供,开发人员当然可以选择任何工具或IDE来编写和调试Spider。

用法示例:

$ scrapy edit spider1

fetch

  • 语法: scrapy fetch
  • 需要项目: 不需要
    使用Scrapy下载器下载给定的URL,并将内容写入标准输出。
    关于此命令的有趣之处在于,它会fetch获取蜘蛛如何下载页面的页面。例如,如果蜘蛛具有覆盖用户代理的USER_AGENT属性,它将使用该属性。
    因此,该命令可用于“查看”您的Spider如何获取特定页面。
    如果在项目外部使用,则不会应用任何特定的行为,它只会使用默认的Scrapy下载程序设置。
    支持的选项:
  • --spider=SPIDER: 绕过蜘蛛自动检测并强制使用特定蜘蛛
  • --headers: 打印响应的HTTP标头,而不是响应的正文
  • --no-redirect: 不遵循HTTP 3xx重定向(默认为遵循它们)
    用法示例:
    
    $ scrapy fetch --nolog http://www.example.com/some/page.html
    [ ... html content here ... ]

$ scrapy fetch --nolog --headers http://www.example.com/
{'Accept-Ranges': ['bytes'],
'Age': ['1263 '],
'Connection': ['close '],
'Content-Length': ['596'],
'Content-Type': ['text/html; charset=UTF-8'],
'Date': ['Wed, 18 Aug 2010 23:59:46 GMT'],
'Etag': ['"573c1-254-48c9c87349680"'],
'Last-Modified': ['Fri, 30 Jul 2010 15:30:18 GMT'],
'Server': ['Apache/2.2.3 (CentOS)']}


###view
* 语法: `scrapy view <url>`
* 需要项目: 不需要
在浏览器中打开给定的URL,就像您的Scrapy蜘蛛会“看到”它一样。有时,蜘蛛人看到的页面与普通用户的页面不同,因此可以用来检查蜘蛛“看到”的内容并确认它是您期望的。
Supported options:

--spider=SPIDER: bypass spider autodetection and force use of specific spider
--no-redirect: do not follow HTTP 3xx redirects (default is to follow them)
Usage example:

$ scrapy view http://www.example.com/some/page.html
[ ... browser starts ... ]
shell
Syntax: scrapy shell [url]
Requires project: no
Starts the Scrapy shell for the given URL (if given) or empty if no URL is given. Also supports UNIX-style local file paths, either relative with ./ or ../ prefixes or absolute file paths. See Scrapy shell for more info.

Supported options:

--spider=SPIDER: bypass spider autodetection and force use of specific spider
-c code: evaluate the code in the shell, print the result and exit
--no-redirect: do not follow HTTP 3xx redirects (default is to follow them); this only affects the URL you may pass as argument on the command line; once you are inside the shell, fetch(url) will still follow HTTP redirects by default.
Usage example:

$ scrapy shell http://www.example.com/some/page.html
[ ... scrapy shell starts ... ]

$ scrapy shell --nolog http://www.example.com/ -c '(response.status, response.url)'
(200, 'http://www.example.com/')

# shell follows HTTP redirects by default
$ scrapy shell --nolog http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F -c '(response.status, response.url)'
(200, 'http://example.com/')

# you can disable this with --no-redirect
# (only for the URL passed as command line argument)
$ scrapy shell --no-redirect --nolog http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F -c '(response.status, response.url)'
(302, 'http://httpbin.org/redirect-to?url=http%3A%2F%2Fexample.com%2F')
parse
Syntax: scrapy parse <url> [options]
Requires project: yes
Fetches the given URL and parses it with the spider that handles it, using the method passed with the --callback option, or parse if not given.

Supported options:

--spider=SPIDER: bypass spider autodetection and force use of specific spider
--a NAME=VALUE: set spider argument (may be repeated)
--callback or -c: spider method to use as callback for parsing the response
--meta or -m: additional request meta that will be passed to the callback request. This must be a valid json string. Example: –meta=’{“foo” : “bar”}’
--cbkwargs: additional keyword arguments that will be passed to the callback. This must be a valid json string. Example: –cbkwargs=’{“foo” : “bar”}’
--pipelines: process items through pipelines
--rules or -r: use CrawlSpider rules to discover the callback (i.e. spider method) to use for parsing the response
--noitems: don’t show scraped items
--nolinks: don’t show extracted links
--nocolour: avoid using pygments to colorize the output
--depth or -d: depth level for which the requests should be followed recursively (default: 1)
--verbose or -v: display information for each depth level
Usage example:

$ scrapy parse http://www.example.com/ -c parse_item
[ ... scrapy log lines crawling example.com spider ... ]

>>> STATUS DEPTH LEVEL 1 <<<
# Scraped Items  ------------------------------------------------------------
[{'name': 'Example item',
 'category': 'Furniture',
 'length': '12 cm'}]

# Requests  -----------------------------------------------------------------
[]
settings
Syntax: scrapy settings [options]
Requires project: no
Get the value of a Scrapy setting.

If used inside a project it’ll show the project setting value, otherwise it’ll show the default Scrapy value for that setting.

Example usage:

$ scrapy settings --get BOT_NAME
scrapybot
$ scrapy settings --get DOWNLOAD_DELAY
0
runspider
Syntax: scrapy runspider <spider_file.py>
Requires project: no
Run a spider self-contained in a Python file, without having to create a project.

Example usage:

$ scrapy runspider myspider.py
[ ... spider starts crawling ... ]
version
Syntax: scrapy version [-v]
Requires project: no
Prints the Scrapy version. If used with -v it also prints Python, Twisted and Platform info, which is useful for bug reports.

bench
New in version 0.17.

Syntax: scrapy bench
Requires project: no
Run a quick benchmark test. Benchmarking.

Custom project commands
You can also add your custom project commands by using the COMMANDS_MODULE setting. See the Scrapy commands in scrapy/commands for examples on how to implement your commands.

COMMANDS_MODULE
Default: '' (empty string)

A module to use for looking up custom Scrapy commands. This is used to add custom commands for your Scrapy project.

Example:

COMMANDS_MODULE = 'mybot.commands'
Register commands via setup.py entry points
Note

This is an experimental feature, use with caution.

You can also add Scrapy commands from an external library by adding a scrapy.commands section in the entry points of the library setup.py file.

The following example adds my_command command:

from setuptools import setup, find_packages

setup(name='scrapy-mymodule',
  entry_points={
    'scrapy.commands': [
      'my_command=my_scrapy_module.commands:MyCommand',
    ],
  },
 )

阅读原文

示例

最好的学习方法是通过示例,Scrapy也不例外。因此,有一个名为quotesbot的示例Scrapy项目,您可以使用它来玩和了解有关Scrapy的更多信息。它包含两个用于http://quotes.toscrape.com的爬虫,一个使用CSS选择器,另一个使用XPath表达式。
quotesbot项目可从以下网址获得:https://github.com/scrapy/quotesbot。您可以在项目的自述文件中找到有关它的更多信息。
如果您熟悉git,则可以checkout签出代码。否则,您可以通过单击此处将项目下载为zip文件。

阅读原文Scrapy tutorial

Scrapy 入门

在本教程中,我们假设您的系统上已经安装了Scrapy。
如果不是这种情况,请参阅安装指南

我们将爬取quotes.toscrape.com,该网站列出了著名作家的名言。
本教程将指导您完成以下任务:

  • 创建一个新的Scrapy项目
  • 编写爬虫以爬网站点并提取数据
  • 使用命令行导出抓取的数据
  • 更改爬虫以递归地跟随链接
  • 使用爬虫参数

Scrapy用Python编写。
如果您是该语言的新手,则可能首先要了解该语言,以充分利用Scrapy。

如果您已经熟悉其他语言,并且想快速学习Python,那么Python教程是一个很好的资源。

如果您不熟悉编程并且想开始使用Python,那么以下书籍可能对您有用:

您还可以查看针对非程序员的Python资源列表,以及Learnpython-subreddit中的建议资源

创建项目

在开始抓取之前,您将必须设置一个新的Scrapy项目。
进入您要存储代码目录,运行:

scrapy startproject tutorial

这将创建一个tutorial目录,其中包含以下内容:

tutorial/
    scrapy.cfg            # deploy configuration file

    tutorial/             # project's Python module, you'll import your code from here
        __init__.py

        items.py          # project items definition file

        middlewares.py    # project middlewares file

        pipelines.py      # project pipelines file

        settings.py       # project settings file

        spiders/          # a directory where you'll later put your spiders
            __init__.py

我们的第一只爬虫

爬虫是您定义的类,Scrapy用于从网站(或一组网站)中获取信息。
他们必须继承Spider的子类,并定义要发出的初始请求,可以选择如何跟随页面中的链接,以及如何解析下载的页面内容以提取数据。

这是我们第一个Spider的代码。
将其保存在项目中tutorial / spiders目录下的quotes_spider.py文件中:

import scrapy


class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        urls = [
            'http://quotes.toscrape.com/page/1/',
            'http://quotes.toscrape.com/page/2/',
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'quotes-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.body)
        self.log('Saved file %s' % filename)

如您所见,我们的Spider从scrapy.Spider创建子类并定义了一些属性和方法:

  • name: 识别爬虫。它在一个项目中必须是唯一的,也就是说,您不能为不同的Spider设置相同的名称。

  • start_requests(): 必须返回一个可迭代的请求(您可以返回一个请求列表或编写一个生成器函数),Spider将从中开始爬行。随后的请求将根据这些初始请求连续生成。

  • parse(): 一个将被调用以处理针对每个请求下载的响应的方法。
    response参数是TextResponse的一个实例,该实例保存页面内容并具有其他有用的方法来处理它。

parse()方法通常解析响应,提取抓取的数据作为字典,还查找要遵循的新URL并从中创建新请求(Request)。

如何运行我们的爬虫

要使我们的爬虫工作,请转到项目的顶级目录并运行:

scrapy crawl quotes

此命令运行带有我们刚刚添加的名称quotes的爬虫,它将发送对quotes.toscrape.com域的一些请求。您将获得类似于以下的输出:

... (omitted for brevity)
2016-12-16 21:24:05 [scrapy.core.engine] INFO: Spider opened
2016-12-16 21:24:05 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-12-16 21:24:05 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (404) <GET http://quotes.toscrape.com/robots.txt> (referer: None)
2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/1/> (referer: None)
2016-12-16 21:24:05 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/2/> (referer: None)
2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-1.html
2016-12-16 21:24:05 [quotes] DEBUG: Saved file quotes-2.html
2016-12-16 21:24:05 [scrapy.core.engine] INFO: Closing spider (finished)
...

现在,检查当前目录中的文件。您应该注意,已经创建了两个新文件:quotes-1.html和quotes-2.html,其中包含我们URL的内容,正如我们的parse方法所指示的那样。

注意

如果您想知道为什么我们还没有解析HTML,请稍候,我们将尽快解决。

到底发生了什么?

Scrapy调度Spider的start_requests方法返回的scrapy.Request对象。
在收到每个响应时,它实例化Response对象并调用与请求关联的回调方法(在本例中为parse方法),并将响应作为参数传递。

start_requests方法的快捷方式

无需实现从URL生成scrapy.Request对象的start_requests()方法,您只需定义带有URL列表的start_urls类属性即可。然后,start_requests()的默认实现将使用此列表来为您的爬虫创建初始请求:

import scrapy


class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = [
        'http://quotes.toscrape.com/page/1/',
        'http://quotes.toscrape.com/page/2/',
    ]

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'quotes-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.body)

即使我们没有明确告诉Scrapy这样做,也会调用parse()方法来处理对这些URL的每个请求。
发生这种情况是因为parse()是Scrapy的默认回调方法,对于没有显式分配的回调的请求会调用该方法。

提取数据

学习如何使用Scrapy提取数据的最佳方法是使用Scrapy shell尝试选择器。运行:

scrapy shell 'http://quotes.toscrape.com/page/1/'

注意

请记住,从命令行运行Scrapy shell时,始终将网址括在引号中,否则包含参数(如&字符)的网址将不起作用。

在Windows上,请使用双引号代替:

scrapy shell "http://quotes.toscrape.com/page/1/"

您会看到类似以下内容:

[ ... Scrapy log here ... ]
2016-09-19 12:09:27 [scrapy.core.engine] DEBUG: Crawled (200) <GET http://quotes.toscrape.com/page/1/> (referer: None)
[s] Available Scrapy objects:
[s]   scrapy     scrapy module (contains scrapy.Request, scrapy.Selector, etc)
[s]   crawler    <scrapy.crawler.Crawler object at 0x7fa91d888c90>
[s]   item       {}
[s]   request    <GET http://quotes.toscrape.com/page/1/>
[s]   response   <200 http://quotes.toscrape.com/page/1/>
[s]   settings   <scrapy.settings.Settings object at 0x7fa91d888c10>
[s]   spider     <DefaultSpider 'default' at 0x7fa91c8af990>
[s] Useful shortcuts:
[s]   shelp()           Shell help (print this help)
[s]   fetch(req_or_url) Fetch request (or URL) and update local objects
[s]   view(response)    View response in a browser

使用命令行,您可以尝试使用带有响应对象的CSS选择元素:

>> response.css('title')
[<Selector xpath='descendant-or-self::title' data='<title>Quotes to Scrape</title>'>]

运行response.css('title')的结果是一个名为SelectorList的类似列表的对象,该对象表示围绕XML / HTML元素的Selector对象的列表,并允许您运行进一步的查询(queries)来细化选择或提取内容数据。

要从上面的标题中提取文本,您可以执行以下操作:

>>> response.css('title::text').getall()
['Quotes to Scrape']

这里有两点需要注意:一是我们在CSS查询中添加了::text,这意味着我们只想直接在<title>元素内选择text元素。如果不指定::text,则会获得完整的title元素,包括其标签(tag):

>>> response.css('title').getall()
['<title>Quotes to Scrape</title>']

另一件事是,调用.getall()的结果是一个列表:选择器有可能返回多个结果,因此我们将它们全部提取出来。
当您知道只想要第一个结果时,在这种情况下,您可以执行以下操作:

>>> response.css('title::text').get()
'Quotes to Scrape'

或者,您可以编写:

>>> response.css('title::text')[0].get()
'Quotes to Scrape'

然而,直接在SelectorList实例上使用.get()可以避免IndexError,并且在找不到与选择匹配的任何元素时返回None

这里有一个教训:对于大多数抓取代码,您希望它能够对由于页面上找不到内容而导致的错误具有弹性,以便即使某些部分未能被抓取,您也至少可以获取一些数据。
除了getall()get()方法之外,您还可以使用re()方法使用正则表达式进行提取:

>>> response.css('title::text').re(r'Quotes.*')
['Quotes to Scrape']
>>> response.css('title::text').re(r'Q\w+')
['Quotes']
>>> response.css('title::text').re(r'(\w+) to (\w+)')
['Quotes', 'Scrape']

为了找到合适的CSS选择器,您可能会发现使用view(response)从Web浏览器的外壳中打开响应页面很有用。您可以使用浏览器的开发人员工具检查HTML并提供一个选择器(请参阅使用浏览器的开发人员工具进行抓取)。

Selector Gadget还是一个不错的工具,可以快速为视觉选择的元素找到CSS选择器,该选择器可在许多浏览器中使用。

XPath: 简介

除了CSS,Scrapy选择器还支持使用XPath表达式:

>>> response.xpath('//title')
[<Selector xpath='//title' data='<title>Quotes to Scrape</title>'>]
>>> response.xpath('//title/text()').get()
'Quotes to Scrape'

XPath表达式非常强大,并且是Scrapy Selectors的基础。实际上,CSS选择器是在后台转换为XPath的。您可以看到,如果您仔细阅读shell中选择器对象的文本表示形式。

尽管XPath表达式可能不如CSS选择器流行,但它提供了更多功能,因为除了导航结构之外,它还可以查看内容。使用XPath,您可以选择以下内容:选择包含文本“下一页”的链接。这使XPath非常适合于抓取任务,并且即使您已经知道如何构造CSS选择器,我们也鼓励您学习XPath,这将使抓取更加容易。

我们不会在这里介绍XPath,但是您可以在此处阅读有关将XPath与Scrapy Selectors结合使用的更多信息。要了解有关XPath的更多信息,我们建议这个通过示例学习XPath教程,和这个学习“如何在XPath中思考”教程

提取名言和作者

现在您对选择和提取有所了解,让我们通过编写代码从网页中提取引号来完善爬虫。
http://quotes.toscrape.com中的每个名言均由如下所示的HTML元素表示

<div class="quote">
    <span class="text">“The world as we have created it is a process of our
    thinking. It cannot be changed without changing our thinking.”</span>
    <span>
        by <small class="author">Albert Einstein</small>
        <a href="/author/Albert-Einstein">(about)</a>
    </span>
    <div class="tags">
        Tags:
        <a class="tag" href="/tag/change/page/1/">change</a>
        <a class="tag" href="/tag/deep-thoughts/page/1/">deep-thoughts</a>
        <a class="tag" href="/tag/thinking/page/1/">thinking</a>
        <a class="tag" href="/tag/world/page/1/">world</a>
    </div>
</div>

让我们打开scrapy shell,玩一会儿,找出如何提取所需的数据:

$ scrapy shell 'http://quotes.toscrape.com'

我们获得带有HTML名言(quote)的选择器的列表,其中包括:

>>> response.css("div.quote")
[<Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' quote ')]" data='<div class="quote" itemscope itemtype...'>,
 <Selector xpath="descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' quote ')]" data='<div class="quote" itemscope itemtype...'>,
 ...]

上面的查询返回的每个选择器都允许我们在其子元素上运行进一步的查询。让我们将第一个选择器分配给变量,以便我们可以直接在特定名言上运行CSS选择器:

>>> quote = response.css("div.quote")[0]

现在,让我们使用刚刚创建的quote对象从该名言中提取文本,作者和标签:

>>> text = quote.css("span.text::text").get()
>>> text
'“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”'
>>> author = quote.css("small.author::text").get()
>>> author
'Albert Einstein'

鉴于标签是字符串列表,我们可以使用.getall()方法来获取所有标签:

>>> tags = quote.css("div.tags a.tag::text").getall()
>>> tags
['change', 'deep-thoughts', 'thinking', 'world']

在弄清楚如何提取每一位之后,我们现在可以遍历所有名言元素并将它们放到Python字典中:

>>> for quote in response.css("div.quote"):
...     text = quote.css("span.text::text").get()
...     author = quote.css("small.author::text").get()
...     tags = quote.css("div.tags a.tag::text").getall()
...     print(dict(text=text, author=author, tags=tags))
{'text': '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”', 'author': 'Albert Einstein', 'tags': ['change', 'deep-thoughts', 'thinking', 'world']}
{'text': '“It is our choices, Harry, that show what we truly are, far more than our abilities.”', 'author': 'J.K. Rowling', 'tags': ['abilities', 'choices']}
...

在我们的爬虫中提取数据

让我们回到爬虫。到目前为止,它没有特别提取任何数据,只是将整个HTML页面保存到本地文件中。让我们将上面的提取逻辑集成到我们的爬虫中。
让我们回到爬虫。到目前为止,它没有特别提取任何数据,只是将整个HTML页面保存到本地文件中。让我们将上面的提取逻辑集成到我们的Spider中。

import scrapy


class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = [
        'http://quotes.toscrape.com/page/1/',
        'http://quotes.toscrape.com/page/2/',
    ]

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').get(),
                'author': quote.css('small.author::text').get(),
                'tags': quote.css('div.tags a.tag::text').getall(),
            }

如果运行此爬虫,它将输出提取的数据和日志:

2016-09-19 18:57:19 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/1/>
{'tags': ['life', 'love'], 'author': 'André Gide', 'text': '“It is better to be hated for what you are than to be loved for what you are not.”'}
2016-09-19 18:57:19 [scrapy.core.scraper] DEBUG: Scraped from <200 http://quotes.toscrape.com/page/1/>
{'tags': ['edison', 'failure', 'inspirational', 'paraphrased'], 'author': 'Thomas A. Edison', 'text': "“I have not failed. I've just found 10,000 ways that won't work.”"}

存储抓取的数据

存储抓取数据的最简单方法是使用Feed导出,并使用以下命令:

scrapy crawl quotes -o quotes.json

这将生成一个quotes.json文件,其中包含所有以JSON序列化的抓取项。

由于历史原因,Scrapy会附加到给定文件,而不是覆盖其内容。如果您两次运行此命令而没有在第二次之前删除该文件,那么最终将得到一个损坏的JSON文件。
您还可以使用其他格式,例如JSON Lines

scrapy crawl quotes -o quotes.jl

JSON Lines格式很有用,因为它像流一样,您可以轻松地向其添加新记录。当您运行两次时,就不会遇到JSON的相同问题。另外,由于每条记录都是单独的一行,因此您可以处理大文件而不必将所有内容都放入内存中,因此有类似JQ的工具可以在命令行中帮助完成此任务。
在小型项目中(例如本教程中的项目),这应该足够了。但是,如果要对已抓取物件(item)执行更复杂的操作,则可以编写物件管道 Item Pipeline。创建项目时,已在tutorial / pipelines.py中为您设置了“Item Pipeline”的占位文件。如果您只想存储已抓取物件,则无需实施任何物件管道。

跟踪链接

假设,您不仅需要从http://quotes.toscrape.com的前两个页面中抓取内容,还希望抓取网站的所有页面中的名言内容。

现在您知道了如何从页面提取数据,让我们看看如何跟踪页面中的链接。

首先是将链接提取到我们要关注的页面。检查我们的页面,我们可以看到带有以下标记的指向下一页的链接:

<ul class="pager">
    <li class="next">
        <a href="/page/2/">Next <span aria-hidden="true">&rarr;</span></a>
    </li>
</ul>

我们可以尝试在shell中提取:

>>> response.css('li.next a').get()
'<a href="/page/2/">Next <span aria-hidden="true">→</span></a>'

这获得了anchor元素,但是我们需要属性href。为此,Scrapy支持CSS扩展,可让您选择属性内容,如下所示:

>>> response.css('li.next a::attr(href)').get()
'/page/2/'

还有一个attrib属性可用(有关更多信息,请参见选择元素属性):

>>> response.css('li.next a').attrib['href']
'/page/2/'

现在让我们看一下我们的Spider,将其修改为以递归方式访问下一页的链接,并从中提取数据:

import scrapy


class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = [
        'http://quotes.toscrape.com/page/1/',
    ]

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').get(),
                'author': quote.css('small.author::text').get(),
                'tags': quote.css('div.tags a.tag::text').getall(),
            }

        next_page = response.css('li.next a::attr(href)').get()
        if next_page is not None:
            next_page = response.urljoin(next_page)
            yield scrapy.Request(next_page, callback=self.parse)

现在,在提取数据之后,parse()方法将查找到下一页的链接,使用urljoin()方法构建完整的绝对URL(因为链接可以是相对的),并产生对下一页的新请求,将其自身注册为回调,以处理下一页的数据提取并保持所有页面的爬取。
您在这里看到的是Scrapy的以下链接机制:当您在回调方法中产生请求时,Scrapy将安排该请求的发送, 并在该请求完成时注册要执行的回调方法。
这么做,您可以构建复杂的搜寻器,并根据定义的规则跟踪链接,并根据其访问的页面提取不同类型的数据。
在我们的示例中创建了一个循环,将其链接到下一页的所有链接,直到找不到该链接为止----便于通过分页方式爬取博客,论坛和其他网站。

创建请求的快捷方式

作为创建请求对象的快捷方式,您可以使用response.follow

import scrapy


class QuotesSpider(scrapy.Spider):
    name = "quotes"
    start_urls = [
        'http://quotes.toscrape.com/page/1/',
    ]

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').get(),
                'author': quote.css('span small::text').get(),
                'tags': quote.css('div.tags a.tag::text').getall(),
            }

        next_page = response.css('li.next a::attr(href)').get()
        if next_page is not None:
            yield response.follow(next_page, callback=self.parse)

scrapy.Request不同,response.follow直接支持相对URL----无需调用urljoin。注意response.follow仅返回一个Request实例;您仍然需要产生此请求。
您还可以将选择器而不是字符串传递给response.follow。该选择器应提取必要的属性:

for href in response.css('ul.pager a::attr(href)'):
    yield response.follow(href, callback=self.parse)

对于<a>元素,有一个快捷方式:response.follow自动使用其href属性。因此,代码可以进一步缩短:

for a in response.css('ul.pager a'):
    yield response.follow(a, callback=self.parse)

要从一个可迭代对象创建多个请求,可以改用response.follow_all

anchors = response.css('ul.pager a')
yield from response.follow_all(anchors, callback=self.parse)

或者,将其进一步缩短:

yield from response.follow_all(css='ul.pager a', callback=self.parse)

更多示例和模式

这是说明回叫和后续链接的另一个爬虫,这次是用于抓取作者信息:

import scrapy


class AuthorSpider(scrapy.Spider):
    name = 'author'

    start_urls = ['http://quotes.toscrape.com/']

    def parse(self, response):
        author_page_links = response.css('.author + a')
        yield from response.follow_all(author_page_links, self.parse_author)

        pagination_links = response.css('li.next a')
        yield from response.follow_all(pagination_links, self.parse)

    def parse_author(self, response):
        def extract_with_css(query):
            return response.css(query).get(default='').strip()

        yield {
            'name': extract_with_css('h3.author-title::text'),
            'birthdate': extract_with_css('.author-born-date::text'),
            'bio': extract_with_css('.author-description::text'),
        }

这个爬虫将从首页开始,它将跟随指向作者页面的所有链接,并为每个页面调用parse_author回调,以及带有parse回调的分页链接(pagination links), 像前面看到的那样。

在这里,我们将回调传递给response.follow_all作为位置参数,以使代码更短;它也适用于request请求。
parse_author回调定义了一个辅助函数,用于从CSS查询中提取和清除数据,并生成包含作者数据的Python字典。
该爬虫演示的另一件有趣的事情是,即使同一位作者的名言很多,我们也不必担心会多次访问同一作者页面。默认情况下,Scrapy过滤掉对已访问URL的重复请求,从而避免了由于编程错误而导致服务器访问过多的问题。可以通过设置DUPEFILTER_CLASS进行配置。
希望到目前为止,您已经对如何在Scrapy中使用跟踪链接和回调的机制有了很好的了解。
作为另一个利用以下链接机制的爬虫示例,请查看CrawlSpider类中的通用爬虫,该类实现了一个小的规则引擎,您可以使用该规则引擎在其上编写爬虫。
同样,一种常见的模式是使用技巧将更多数据传递给回调,从而使用来自多个页面的数据来构建项目。

使用爬虫参数

您可以在运行爬虫时使用-a选项来为爬虫提供命令行参数:

scrapy crawl quotes -o quotes-humor.json -a tag=humor

这些参数会传递给Spider的__init__方法,并默认成为爬虫属性。

在此示例中,为tag参数提供的值可通过self.tag获得。您可以使用它使您的Spider只获取带有特定标记的名言,并根据参数构建URL:

import scrapy


class QuotesSpider(scrapy.Spider):
    name = "quotes"

    def start_requests(self):
        url = 'http://quotes.toscrape.com/'
        tag = getattr(self, 'tag', None)
        if tag is not None:
            url = url + 'tag/' + tag
        yield scrapy.Request(url, self.parse)

    def parse(self, response):
        for quote in response.css('div.quote'):
            yield {
                'text': quote.css('span.text::text').get(),
                'author': quote.css('small.author::text').get(),
            }

        next_page = response.css('li.next a::attr(href)').get()
        if next_page is not None:
            yield response.follow(next_page, self.parse)

如果您将tag=humor参数传递给该爬虫,您会注意到它只会访问来自humor标签的URL,例如http://quotes.toscrape.com/tag/humor
您可以在此处了解有关处理爬虫参数的更多信息

下一步

本教程仅介绍了Scrapy的基础知识,但此处未提及许多其他功能。检查Scrapy概览中的还有什么?一章,其中快速概述了最重要的主题。
您可以从“基本概念”部分继续,以进一步了解命令行工具,爬虫,选择器以及本教程未涵盖的其他内容,例如对抓取的数据进行建模。如果您喜欢玩示例项目,请查看“示例”部分。

敏捷思想当然最准确是敏捷宣言所讲的。我用我自己的理解表述下:
敏捷就是大事化小,小事化了。
大事化小,其实这个似乎和传统项目管理的工作分解Work Break Down(WBD)类似,也和很多老外说的做事方式颇为相通。然而其中有个重要区别:敏捷是大事化小事,WBD是大事化小步。
小事化了。敏捷的每一件小事都是完整的事件,需要同大事一样有完整的流程,包括从设计到执行到检验的全过程。这是与传统WBD的最大不同。WBD只能说是把一件事分成了很多步骤,而不能说分成了很多小事。小事化了意味着此事的完成,WBD一小步的完成却不能意味任何事情的完成。
所以,每一件小事都是可呈现的。每一件小事之间的有机连接成就了大事。

微信开发者社区在18年就有人提出这个问题,当时说是不行.然而提问者说为什么另外一家小温智能可以?
经过自行测试,发现通过微信接口是可以以AP模式进行设置的. 因为微信小程序WIFI有两个能力:获取周围SSID,以及连接SSID.
SDK文档

获取SSID方式

在app.json中获取地理位置能力

  "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序连接WIFI"
    }

在页面js中onGetWifiList->startWifi->getWifiList. 微信小程序比较神奇的地方是,get信息的函数居然不是直接返回信息,而是只返回成功失败, 然后发出一个事件,你得再用另一个专门监听这个事件的函数来得到信息. 感觉脱裤子放屁一样.

  onReady: function () { //启动后先监听获取到WIFILIST的事件
    wx.onGetWifiList(function (res){
      console.log(res)
    })
  },
  startwifi:function(){ //启动WIFI接口,事实上不是开启设备的WIFI,只是开启小程序的WIFI能力
    wx.startWifi({
      success(res) {
        console.log(res.errMsg)
      }
    })
  },
  getwifilist: function () { //获取WIFILIST, 成功后发出事件会被前面的监听捕获
    console.log('getwifilist')
    wx.getWifiList({
      complete(res) {
        console.log(res)
      }
    })
  },

WIFILIST的形式:

{wifiList: []}

Android举例(从console输出COPY来的)

wifiList: Array(24)
0: {SSID: "KK5G", BSSID: "xx:xx:xx:xx:xx:xx", secure: true, signalStrength: 77}
1: {SSID: "DIRECT-5BDESKTOP-0M7QR80msVL", BSSID: "xx:xx:xx:xx:xx:xx", secure: true, signalStrength: 99}
2: {SSID: "ChinaNet-UFsN", BSSID: "xx:xx:xx:xx:xx:xx", secure: true, signalStrength: 44}
3: {SSID: "KK", BSSID: "xx:xx:xx:xx:xx:xx", secure: true, signalStrength: 46}

IOS举例, 居然元素结构和Android不同. signalStrength的定义也不一样,一个是整数一个是纯小数.幸好SSID和BSSID两个字段是一样的.
IOS还有个问题,wx.onGetWifiList在ios中不进入回调,幸好官方有回答,是getWifiList以后会调起微信权限页面,上退一级到设置主页面,再点击WIFI,刷出来列表后才能收到onGetWifiList的回调.

wifiList: Array(18)
0: {SSID: "ROADSUN2", autoJoined: false, signalStrength: 0.26170599460601807, justJoined: false, BSSID: "xx:xx:xx:xx:xx:xx", …}
1: {SSID: "TP-LINK_090C", autoJoined: false, signalStrength: 0.3535159230232239, justJoined: false, BSSID: "xx:xx:xx:xx:xx:xx", …}
2: {SSID: "office1_2.4GHz", autoJoined: false, signalStrength: 0.39624282717704773, justJoined: false, BSSID: "xx:xx:xx:xx:xx:xx", …}
3: {SSID: "408a", autoJoined: false, signalStrength: 0.5117818117141724, justJoined: false, BSSID: "xx:xx:xx:xx:xx:xx", …}
4: {SSID: "ChinaNet-ePMi", autoJoined: false, signalStrength: 0.5352672934532166, justJoined: false, BSSID: "xx:xx:xx:xx:xx:xx", …}

//展开一个元素:
{
BSSID: "xx:xx:xx:xx:xx:xx"
SSID: "ROADSUN2"
autoJoined: false
justJoined: false
secure: true
signalStrength: 0.26170599460601807
}

可以看到返回值里居然没有WIFI类型是2.4G还是5G...

可能的设置方式

设置过程如下:

  1. 智能设备进入Station模式, 扫描周围WIFI SSID,先存下来
  2. 智能设备进入AP模式, 等待小程序连接
  3. 小程序获取周围WIFI SSID, 这儿要区分下IOS和Android,两者体验不同.(此步骤也可省略,以智能设备获取的为准)
  4. 小程序连接智能设备AP
  5. 小程序通过API获取智能设备的SSID
  6. 小程序的SSID和智能设备的SSID取交集, 供用户选择(筛选出2.4G WIFI)
  7. 用户选择并输入密码
  8. 小程序自己先试试能不能连接上,尝试的过程中会断开与智能设备的链接,如果密码错误让用户重新输入
  9. 小程序链接成功后,再次链接智能设备的AP, 正式通知智能设备链接WIFI.
  10. 完成后,小程序自行重新连接WIFI. 结束.

兼容性问题和系统差异

  • 对版本要求: 小程序1.6.0,现在99.99%已经支持.
  • getWifiList这个接口iOS 将跳转到系统的 Wi-Fi 界面,Android 不会跳转。 iOS 11.0 及 iOS 11.1 两个版本因系统问题,该方法失效。但在 iOS 11.2 中已修复。
  • iOS11.0是2017.9.17发布,2017年10月31日发布11.2的首个beta版. 同期2017年9月13日发布的手机是,第十一代iPhone 8,iPhone 8 Plus,iPhone X
  • connectWifi仅 Android 与 iOS 11 以上版本支持. 现在的版本已经是13.3.

国外

github不用说了,只是私有库要收费
gitlab也是极好的, 尤其是自建私服首选

国内

码云gitee是OSCHINA的团队, 虽然是个深圳的不大的公司,但支持私有库嘛,虽然国内对隐私保护都很可疑. 所有私有库协作人数累计不超过5个.
coding.net, 也在深圳,似乎现在要被腾讯收了, 腾讯的托管平台叫腾讯云开发者平台现在注册的话会直接跳转coding. coding号称是以团队方式注册,5人以下团队免费. 里面不止有git仓库,还有整套敏捷管理, 比较像是tapd+github,甚至额外还有些持续集成持续测试.
阿里云托管平台, 登录逻辑很奇怪,使用阿里云账户登陆后, 又要让我另外再建立一个账号.对仓库数目有限制,50个.可以建立私人库. 嗯,这个限制数目的态度感觉会很不待见啊

git地址
文档地址
软件地址,Windows根据目前推荐是4.0最好
识别库地址,要把根目录下的chi_sim.traineddata和chi_sim_vert.traineddata放到安装目录tessdata下,把script里面的HanS.traineddata和HanS_vert.traineddata放到tessdata\script下。还不太明白script和外面的文件的关系。
试了下,效果还行。英文效果比中文好不少。似乎中文还是贡献率太低。
用法也简单。

tesseract imagename outputbase [-l lang] [-psm pagesegmode] [configfile...]
tesseract myscan.png out
tesseract myscan.png out -l deu
tesseract myscan.png out -l eng+deu
tesseract myscan.png out -l chi_sim hocr
tesseract myscan.png out pdf

其中hocr是一个xml文件,里面有对应文字的坐标信息,应该比较适合于做自动化。
试了下,同样的图片,白底黑字比黑底白字识别率好非常多。

x = {
a:1, 
b:function (){return this.a}, // OK,可以访问,this指的是x
b(){return this.a}, //OK,上面的简写形式.
c:()=>{return this.a} //Error! 箭头函数的this似乎在上一层,x同级的一层,global.
}