- Keymaps and Keyboard Input
- In this document
- Functionality
- Key Layout Map
- Selection of a Key Layout Map
- File Format
- Example of a Key Layout Map File
- Key Character Map
- Selection of a Key Character Map
- File Format
- Example of a Key Character Map File
- Resource Binary File Format
- Implementing Your Own Driver (Driver Template)
- Sample Implementation
- Android key code names
Keymaps and Keyboard Input
In this document
This document describes how keyboard input gets translated into Android actions and how you can customize key layout and key character maps to match the needs of your own device.
Android uses the standard Linux input event device ( /dev/event0 ) and driver as described in the linux/input.h kernel header file. For more information regarding standard Linux input drivers, please see Linux Input drivers at http://kernel.org.
Functionality
Android’s input event device is structured around an interrupt or polling routine that captures the device-specific scancode and converts it to a standard form acceptable to Linux (as defined in input.h ) before passing it to the kernel with input_event() .
The keymap driver’s other primary function is to establish a probe function that sets up the interrupt or polling function, handles hardware initialization, and attaches the driver to the input subsystem with input_register_device() .
The table below describes the steps required to translate from keyboard input to application action:
Step | Action | Explanation |
---|---|---|
1. | Window manager reads key event from Linux keyboard driver. | Events are typically positional. For example, the top-left position on a keypad returns 16 regardless of whether that key is printed with a Q (as on a QWERTY keypad) or an A (as on an AZERTY keypads). This first conversion by the Linux Keyboard Driver yields a scancode (for example, 16). |
2. | Window manager maps scancode to keycode. | When the window manager reads a key event out of the driver, it maps the scancode to a keycode using a key layout map file. Typically, the keycode is the primary symbol screen-printed on a key. For example, KEYCODE_DPAD_CENTER is the center button on the five-way navigation control. Even though ALT + G generates a «?» character, KEYCODE_G is the keycode. |
3. | Window manager sends both the scancode and the keycode to the application. | Both the scancode and keycode are handled by the view with focus. How the application interprets both depend on the application. |
Key Layout Map
Selection of a Key Layout Map
Key layout maps are installed in /system/usr/keylayout and /data/usr/keylayout .
For each keyboard device xxx, set the android.keylayout.xxx system property (see Building New Device for help setting system properties). If you don’t specify a keylayout file, Android will default to /system/usr/keylayout/qwerty.kl .
File Format
Key layout maps are stored on the device as UTF-8 text files and have the following characteristics:
- Comments: The pound symbol (#) denotes a comment and everything after the pound symbol on a line is ignored.
- Whitespace: All empty lines are ignored.
- Key definitions: Key definitions follow the syntax key SCANCODE KEYCODE [FLAGS. ] , where SCANCODE is a number, KEYCODE is defined in your specific keylayout file ( android.keylayout.xxx ), and potential FLAGS are defined as follows:
- SHIFT: While pressed, the shift key modifier is set
- ALT: While pressed, the alt key modifier is set
- CAPS: While pressed, the caps lock key modifier is set
- WAKE: When this key is pressed while the device is asleep, the device will wake up and the key event gets sent to the app.
- WAKE_DROPPED: When this key is pressed while the device is asleep, the device will wake up and the key event does not get sent to the app.
Example of a Key Layout Map File
The following code comes from android/src/device/product/generic/tuttle2.kl and is an example of a complete key layout file:
Key Character Map
Selection of a Key Character Map
Key character maps are installed in /system/usr/keychars and /data/usr/keychars .
For each keyboard device xxx, set the android.keychar.xxx system property to the full path of the desired keychar file. If you don’t specify a keychar file, Android will default to /system/usr/keychar/qwerty.kl .
File Format
Key character maps are stored on the device as binary resources in order to reduce loading time. Key character maps have the following characteristics:
- Comments: The pound symbol (#) denotes a comment and everything after the pound symbol on a line is ignored.
- Whitespace: All empty lines are ignored.
- Column definitions: Column definitions follow the syntax columns MODIFIERS [. ] , where MODIFIERS are defined as follows:
Character in MODIFIERS Corresponding bit in the modifiers O no modifiers S MODIFIER_SHIFT C MODIFIER_CONTROL L MODIFIER_CAPS_LOCK A MODIFIER_ALT - Key definitions: Key definitions have the syntax key SCANCODE CHARACTER [. ] where SCANCODE is a number and CHARACTER values are either UTF-8 characters in quotation marks (for example, «a») or a numeric value that strtol can parse.
Example of a Key Character Map File
The following code comes from android/src/device/product/generic/tuttle2.kcm and represents a complete key character file:
The type line indicates what kind of keyboard your device implements. Possible types include:
- NUMERIC: A numeric (12-key) keyboard.
- Q14: A keyboard that includes all letters but multiple letters per key.
- QWERTY: A keyboard with all letters and possibly numbers. This option applies to all full keyboard configurations, such as AZERTY.
Resource Binary File Format
The file snippet above gets converted to the following by the makekcharmap tool as part of the build process. You can mmap this file in and share the approximately 4k of memory that it uses between processes to minimize load time.
Offset | Size (bytes) | Description |
---|---|---|
0x00-0x0b | The ascii value «keycharmap1» including the null character | |
0x0c-0x0f | padding | |
0x10-0x13 | The number of entries in the modifiers table (COLS) | |
0x14-0x17 | The number of entries in the characters table (ROWS) | |
0x18-0x1f | padding | |
4*COLS | Modifiers table. The modifier mask values that each of the columns in the characters table correspond to. | |
padding to the next 16 byte boundary | ||
4*COLS*ROWS | Characters table. The modifier mask values that each of the columns correspond to. |
Implementing Your Own Driver (Driver Template)
The following file, pguide_events.c , illustrates how to implement an Android keymap driver.
Sample Implementation
Assume the following for the setup of a new keypad device:
The following example log file indicates that you have correctly registered the new keypad:
The snippet above contains artificial line breaks to maintain a print-friendly document.
Источник
Android key code names
Так как подобной темы нет, а информация по данному вопросу разбросана небольшими частями по различным темам форума решил, создать данную тему с общей инструкцией.
Для всех действий необходим root.
Работать будем с файлами расположенными в system\usr\keylayout
Остановимся на файлах, которые необходимо редактировать (это, пожалуй, самый сложный этап):
Имя файла зависит от фирмы производителя, модели и версии прошивки, но как я заметил есть следующая тенденция: до Android 2.3.5 включительно, имя нужного нам файла формировалоcь следующим образом ***-keypad.kl (или ***- kpd.kl), где *** — заводское имя вашей модели.
- Известные мне примеры:
- Gigabyte Gsmart G1310 — qrd-keypad.kl
- Gigabyte Gsmart G1355 – msm7627_sku5_keypad.kl
- LG P500 Optimus One – thunder_keypad.kl
- LG E405 Optimus L3 Dual — surf_keypad.kl и 7x27a_kp.kl
- LG E730 Optimus Sol – victor-keypad.kl (touch-keypad.kl)
- LG GT450 – swift.kl (не уверен, но люди пишут)
- HTC Hero — heroc-keypad.kl
- HTC Desire — bravo-keypad.kl
- HTC Explorer — pico-keypad.kl
- HTC Desire S — saga-keypad.kl
- HTC Desire HD — spade-keypad.kl
- HTC Sensation — pyramid-keypad.kl
- Samsung Galaxy S I9000 — melfas-touchkey.kl и s3c-keypad.kl
- SE Live with Walkman — pm8058-keypad.kl и msm_pmic_pwr_key.kl (во втором файле только кнопка питания)
- Sony Ericsson Xperia X8 – shakira-keypad.kl
- Sony Ericsson Xperia X10 – es2009ra_keypad.kl
- Star A2000 / A2000 GPS — MT6516-kpd.kl и QWERTY.kl
* — планируется наполнение списка с Вашей помощью, если есть замечания указывайте.
Начиная с 4.0.3 всё изменилось, могу отметить, что для HTC вторая часть файла стала touchscreen.
Известные мне примеры:
* — планируется наполнение списка с Вашей помощью, если есть замечания указывайте.
Файлы кнопок проводной гарнитуры обычно имеют вид:
- POWER – блокировка/разблокировка
- HOME – возврат на основной экран
- MENU – вызов меню
- BACK — возврат к предыдущему действию
- SEARCH – вызов поиска
- VOLUME_DOWN – понижение уровня громкости
- VOLUME_UP – повышение уровня громкости
- CALL – вызов Phone.apk (позволяет отвечать на вызов)
- ENDCALL – завершение звонка
- CAMERA – вызов Camera.apk
- FOCUS – автофокус
- DPAD_CENTER – курсор (касание) по центру
- DPAD_UP – курсор (касание) вверх*
- DPAD_DOWN – курсор (касание) вниз*
* — установка этих значений на кнопки 115 и 114 соответственно позволяет добиться пролистывания текстов или страницы браузера кнопками громкости. - DPAD_LEFT – курсор (касание) влево
- DPAD_RIGHT – курсор (касание) вправо
- MUTE – выключение звука музыки без остановки трека
- MEDIA_NEXT – следующий трек
- MEDIA_PLAY_PAUSE – проигрывать/пауза
- MEDIA_STOP – остановить трек
- MEDIA_PREVIOUS – предыдущий трек
- MEDIA_REWIND — перемотка
- MEDIA_FAST_FORWARD – ускорить воспроизведение
- HEADSETHOOK – кнопка гарнитуры – позволяет отвечать на вызовы, класть трубку и управлять плеером
- GRAVE — ?
- APP_SWITCH (RECENT_APP) – вызов панели «Недавние» с возможностью переключаться между приложениями (либо вызов диспетчера приложений в зависимости от прошивки.
Также следует обратить внимание на такие дополнительные параметры как:
Если стоит WAKE то после нажатия в спящем режиме смарт «проснётся» и выполнит действие, а при WAKE_DROPPED просто «проснётся», без передачи кода кнопки на выполнение.
- Если у вас кастомный recovey (а вероятней всего он у вас такой), то во вкладке advanced можно воспользоваться функцией key test.
- Программа KeynrTracker.
KeynrTracker.apk ( 8.32 КБ )
Программа Keycode CheckerKeycodeChecker.apk ( 10.3 КБ )
- Самый простой способ. Заключается в редактировании нужных файлов прямо в папке keylayout, для этого используем ES Проводник (RootExplorer, Total Commander, ну или что-то на свой вкус (я пользуюсь ES Проводником и вам советую)): открываем – меняем требуемые значения – закрываем с сохранением изменений – перезагружаем девайс. При этом в папке keylayout будет создан фаил ****.kl.bak в котором сохранятся первоначальные значение изменённого вами файла. Также можно редактировать копию файла на SD карте или ПК, а затем вставлять с заменой в keylayout.(Проверено)
Программа Easy Android Tools (EAT). Программа позволяет подключать телефон как через USB кабель так и по WiFi. После подключения и распознания телефона программой в правом окне Вы увидите содержимое внутренней памяти телефона. Переходим в Необходимо system/usr/keylayout, находим нужный фай, редактируем его в EAT Editor (F4), сохраняем изменения, перегружаем смарт и готово. (Программа подразумевает наличие на вашем ПК USB драйверов для вашего устройства (их можно найти на оф сайте программы), и HTC Syns для HTC)EAT_1.3.1.RUS.Setup.exe ( 1.78 МБ )
Для этого метода нам потребуется Android SDK tools, знание точного названия файл который нам надо менять (можно посмотреть через ES Проводник и тд. и. тп.)
В командной строке переходим в папку с Android SDK tools (у меня это C:\Android), далее выполняем следующее. (Необходимо наличие на вашем ПК USB драйверов для вашего устройства)
Перегружаем аппарат и готово. Android.zip ( 572.31 КБ )
(Проверено)
(Проверено)
ButtonRemapper – позволяет переназначать кнопки, но работает некорректно на многих устройствах особенно с android 4.0.3 и выше. Более разработчиком не поддерживается, Следует отметить, что в теме по этому приложению достаточно много информации по ручному переназначению кнопок.
ButtonRemapper Galaxy Tab Tab_ButtonRemapper_v1.1.apk ( 67.09 КБ )
ButtonRemapper Galaxy S ButtonRemapper_Galaxy_S.apk ( 72.76 КБ )
Headset Button Controller – управление музыкальным проигрывателем и другими функциями телефона с проводной гарнитуры.
DreamKeys – программа для переназначения кнопок телефона, идея заключается в перехвате команд нажатий и присвоение им других действий, root не нужен (возможна настройка на долгое нажатие).
Сообщение отредактировал dеym — 26.07.19, 16:29
Источник