Android SharedPreferences Tutorial and Example

Building a custom Android shortcut keyboard

Android apps often ask users to repeat small tasks: open a date picker, insert a saved address, start a timer, or jump to a favourite screen. A shortcut keyboard turns these actions into memorable sequences, reducing taps while preserving Android’s familiar editing flow.

Implementing a custom keyboard shortcuts system can happen at two levels. A custom input method built with InputMethodService can handle hardware key chords and its own on-screen keys. An in-app shortcut handler is easier to contain, but it only works inside that application and cannot help with text fields elsewhere.

Australia makes the use case especially practical. Commuters in Sydney and Melbourne often check messages or draft notes on trains and buses with one hand occupied, while voice dictation has become an everyday habit. Android has a substantial share of the local handset market, although iPhone remains common, so the keyboard should be useful with touch, a hardware keyboard, and speech input.

Privacy matters because an input method can observe everything typed through it. Under the Privacy Act 1988 and the Australian Privacy Principles, an Australian operator collecting or storing typed information may need clear disclosure, security safeguards, and deletion controls. Sensitive content should be processed locally rather than sent to a server by default.

Decide where the shortcut logic belongs

Start with a feature inventory and choose the narrowest scope that meets the need. App-specific actions, such as switching a drawing canvas to a new colour, belong in the app’s own command or shortcut layer. Text expansions such as inserting an email signature work well in an input method because they can be reused across email, chat, and note-taking apps.

A custom keyboard also creates more obligations than an ordinary text field. Users must enable it in Android’s language and input settings, and switching between keyboards can interrupt fast typing. Treat it as an optional productivity tool: retain the system keyboard, make activation obvious, and provide a quick route back to the previous input method.

Capture key events without breaking normal typing

InputMethodService supplies the lifecycle hooks for an input method. In onStartInput, inspect the EditorInfo to learn the field type and available editor options. For hardware input, handle key events in onKeyDown; for an on-screen panel, provide an InputView and send chosen commands through the same resolver.

Use distinct chords for global actions and reserve familiar editing combinations for the platform. A modifier plus a normal letter can be expanded into text, but intercepting Ctrl+C or Ctrl+V in every field would be disruptive. Returning true only after a shortcut matches also lets unmatched keys reach the editor.

override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
    if (event.action == KeyEvent.ACTION_DOWN &&
        event.isCtrlPressed && event.isAltPressed &&
        keyCode == KeyEvent.KEYCODE_T) {
        resolver.resolve("timestamp")?.let {
            commitText(it)
            return true
        }
    }
    return super.onKeyDown(keyCode, event)
}

Touch users need an equally discoverable path, such as a labelled strip above the keys or a dedicated shortcut mode. On public transport or during a hands-busy meeting, a voice command implementation can provide a separate speech-based route, while keyboard chords remain useful when precise text entry is required.

Resolve shortcuts against the editor context

Store each shortcut as a stable identifier, optional trigger sequence, and expansion function rather than as a long block of duplicated text. A resolver can match a prefix such as :sig or a chord such as Ctrl+Alt+T, then return the current value. This keeps bindings editable and allows temporary values, such as today’s date, to be calculated at use time.

Context determines whether expansion is safe. Check EditorInfo hints and input types, and do not expand snippets in password or secure fields. Some fields may only indicate that they accept text, so an explicit opt-in setting is safer than guessing from a package name. When a shortcut triggers an action instead of inserting text, restrict it to allowlisted apps and confirm destructive operations.

Approach Best suited to Context available Typical complexity
Custom IME with on-screen keys Reusable snippets across apps Editor metadata and selected text High
Hardware chord handler in an IME Fast power-user input Key events and editor metadata Medium
In-app shortcut layer Commands tied to one app Full application state Low to medium

Protect user data and support accessible input

A shortcut engine does not need network access to work. Keep dictionaries and personal snippets in app-private storage, avoid recording raw keystrokes, and make any optional synchronisation explicit and revocable. If data leaves the device, document the purpose, recipients, retention period, and deletion route before collection. This simple data flow makes compliance with the Privacy Act easier to demonstrate.

Do not retain full expansions that contain passwords, one-time codes, card numbers, or medical details. Let users import a business signature or address book through a separate settings screen where they can review each item. Keys held in Android Keystore can protect especially sensitive fragments, although encryption does not replace sensible collection limits.

Accessible input also affects shortcut design. Support TalkBack labels, visible focus order, large touch targets, and alternatives to chord-only commands. The Disability Discrimination Act 1992 is relevant to many Australian businesses and government services, and a keyboard that works only for expert hardware users can exclude people who rely on assistive technology.

Persist preferences and personalise the experience

For a small set of user-defined bindings, SharedPreferences is sufficient: store shortcut identifiers, enabled states, and display labels, then load them into the resolver when the service starts. DataStore offers a more scalable option for larger libraries, background updates, and structured migration. Provide export, import, reset, and conflict handling so a changed binding never silently overwrites user data.

Use Android locale data instead of hard-coded English formats. Offer an English (Australia) subtype, respect the user’s date and time preferences, and spell common terms in Australian English. If an expansion contains a date, format it when the shortcut fires rather than storing a value that becomes stale.

Test, release, and maintain the shortcut keyboard

Test the resolver as ordinary unit code, then exercise the service in real fields with adb or instrumented tests. Cover ordinary text, email, search, password, and multiline fields; portrait and landscape layouts; app switching; voice input; and both physical and on-screen keys. Check that Back, Enter, selection, copy, and paste still behave normally after a shortcut fires.

Before release, document every expansion, data use, and network permission in the Google Play listing and privacy policy. Keep a rollback path that disables faulty bindings without blocking the keyboard, and test upgrades against existing preferences. Version the shortcut format so old entries can be migrated safely.

  • Begin with a small, visible set of abbreviations and reserve chords for actions that are genuinely repeated.
  • Show each shortcut and its expansion in settings, with one-tap editing and a reset option.
  • Never expand snippets in secure fields, and provide a visible way to pause custom suggestions.
  • Log only anonymous, local failure counters during development; never store the text that triggered a shortcut.