Bitbang3r
Bitbang3r

Reputation: 6904

How to create Android KeyEvent for arbitrary Unicode character?

I'm writing an IME. As you'd expect, it extends InputMethodService.

In onCreate(), I'm obtaining a KeyCharacterMap:

keyCharacterMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);

I need a way to inject phantom keypresses for arbitrary Unicode characters. My first stab looked something like this:

public void generatePhantomKeypress(char[] c) {
    KeyEvent[] keySequence = charMap.getEvents(c);
    for (KeyEvent k : keySequence)
        getCurrentInputConnection().sendKeyEvent(k);
}

It works for letters, digits, and some punctuation marks, but it only seems to work for characters you can enter directly (without deadkey-gymnastics or using the alt keypad) on a PC keyboard.

Some specific characters that cause charMap.getEvents(...) to return null when passed a char[] with a single element whose value is among the following:

TL/DR: given a char whose value is some arbitrary Unicode value, how do you convert it into a KeyEvent (or sequence of KeyEvent objects) that, when passed to sendKeyEvent(), will cause Android to act as if you entered that character directly from a phantom keyboard?

Upvotes: 1

Views: 1041

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93668

Normally an IME doesn't generate key events. It usually uses inputConnection.commit() to send data to the application. That API takes any CharSequence (which can even include limited styling).

Upvotes: 1

Related Questions