Writing an Android keyboard (InputMethodService)
androidimekeyboardinputmethodserviceinputconnectionaccessibilitykotlin
Justin's Keyboard (~/dev/⌨️, package com.justinahampton.keyboard) is a native Android input method in plain Kotlin with zero library dependencies: one custom View draws every key, and an InputMethodService talks to apps through InputConnection. These are the platform facts and traps learned building it.
Field types decide behavior
EditorInfo.inputType tells you what the field is. Classify it in one pure function and test it:
- Password variations (text, web, visible) and PINs (TYPE_CLASS_NUMBER + NUMBER_VARIATION_PASSWORD, which was missed at first) are secret: no learning, no clipboard history, no key popups, no tap logging, no suggestions.
- IME_FLAG_NO_PERSONALIZED_LEARNING (incognito) means do not learn.
- Email, URL, filter and "no suggestions" fields get only what they ask for, with one exception: address bars are mostly typed searches, so word suggestions there help even when the field sets NO_SUGGESTIONS (details in Keyboard autocorrect, next-word prediction and learning).
Send versus new line
A multi-line field that asks for IME_ACTION_SEND (a chat composer with ImeAction.Send in Compose) gets a Send key, and an IME that honors it leaves no way to type a line break. SMS itself carries newlines fine. The keyboard-side fix: when the action is not plain Return and the field is TYPE_TEXT_FLAG_MULTI_LINE, a long press on Enter commits "\n" (after the usual autocorrect path) and releasing sends nothing; draw a small return arrow in the key's corner and expose an accessibility long-click action "New line". Tap still sends. The app-side alternative is not to request Send on multi-line composers.
Auto-capitalization
getCursorCapsMode(info.inputType) only returns sentence caps if the app set TYPE_TEXT_FLAG_CAP_SENTENCES. Many apps never do; Flutter's TextField defaults to none, so text in Flutter apps never auto-capitalized. Force sentence caps in ordinary text fields, falling back to TextUtils.getCapsMode on the text before the cursor.
Editing text safely
- Keep "what one backspace takes back" (an autocorrection, a glided word, an added space) tied to an absolute cursor anchor from
getExtractedText, not just to matching text. Otherwise moving the cursor behind another identical word and pressing backspace "undoes" a correction that never happened there. - Check for a selection first in every key handler.
- Skip autocorrect, learning and shortcut expansion when the cursor is mid-word (a letter or digit follows it), or "jhampton|io" + "." becomes "Hampton.io".
onStartInputView(info, restarting = true)on the same field must keep mode, shift, and edit state.- A field that calls
restartInputon every change breaks any "delete then commit" pair (the connection dies between the two). The robust approach issetComposingRegionplus a singlecommitText. - Move the cursor by grapheme with
setSelection, not by repeated DPAD events.
Real key events (Ctrl, Alt, Esc, arrows, F-keys)
Send through InputConnection.sendKeyEvent with deviceId KeyCharacterMap.VIRTUAL_KEYBOARD, flags FLAG_SOFT_KEYBOARD | FLAG_KEEP_TOUCH_MODE, and wrap each chord in modifier down/up events with the right meta state. KeyCharacterMap.getEvents gives the key code for a character; characters with no key (é, €, emoji) are committed as text. Esc in an ordinary app acts as Back. A stock EditText collapses a Shift+Arrow selection on the second press in a row (same with Gboard), a field quirk not an IME bug.
Permissions from an IME
An IME cannot show a runtime permission dialog. For the microphone, start the settings activity with an extra that asks for RECORD_AUDIO and finishes on grant. Voice typing with the framework SpeechRecognizer needs a <queries> entry for android.speech.RecognitionService; partial results go in as composing text and finals are committed.
Opening your settings from the keyboard
Start the activity with FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK; clearing the task makes Back return to the app being typed in even if settings was already open in the background.
Accessibility
One custom view with no child views is invisible to TalkBack. Implement virtual accessibility nodes (an ExploreByTouchHelper-style provider) for every key and suggestion. Side benefit: uiautomator dump --windows then lists every key by label, which makes automated QA possible.
Settings that apply live
Listen to SharedPreferences changes for an explicit set of "live" keys and rebuild the view; a new setting must be added to that set. Rebuilt input views need requestApplyInsets().
Privacy and backups
Exclude learned words and personal data from Android backup in both res/xml/backup_rules.xml and data_extraction_rules.xml (API 31+), for example domain="database" path=".". Keep clipboard history in memory only unless the user pins an item.
Gotchas
isSingleLine = trueon a passwordEditTextsilently unmasks it; settransformationMethodinstead.- A plain
Viewwith WRAP_CONTENT takes all offered space; measure spacers exactly. ime enableright after install can fail; force-stop or reinstall deselects the IME (see Driving the Android emulator headlessly for QA).
See also
- Keyboard autocorrect, next-word prediction and learning
- Emoji suggestions from Unicode CLDR keyword data
- Alt codes and typing any Unicode character
- Android window insets, the soft keyboard, and edge-to-edge
Linked from
- Alt codes and typing any Unicode character
- Android window insets, the soft keyboard, and edge-to-edge
- Driving the Android emulator headlessly for QA
- Emoji suggestions from Unicode CLDR keyword data
- Generating app assets with Python scripts (logos, GIFs, sounds)
- Keyboard autocorrect, next-word prediction and learning
- Keyboard hit areas that follow the user's taps (a personal touch model)
- Keyboard, Justin's Android input method (overview and canon)