I have edited the SoftKeyboard IME Android sample code to pass a custom KeyEvent to my application. I do this using this KeyEvent Constructor:
private void handleCharacter(int primaryCode, int[] keyCodes) {
if (isInputViewShown()) {
if (mInputView.isShifted()) {
primaryCode = Character.toUpperCase(primaryCode);
}
}
if (isAlphabet(primaryCode)) {
String characterString = new String();
for (int c : keyCodes) {
characterString += (char)c;
}
Log.e(TAG, "sending: " + characterString);
KeyEvent ke = new KeyEvent(SystemClock.uptimeMillis(),
characterString, 0, KeyEvent.FLAG_CANCELED);
getCurrentInputConnection().sendKeyEvent(ke);
}
}
In my Application, I have a CustomTextView that I have set up following this thread, and I've written the onKey()
thus:
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d(TAG, "onKeyListener");
CustomEditor context = (CustomEditor) mWeakContext.get();
assertNotNull("Context invalid", context);
if (event.getAction() == KeyEvent.ACTION_UP) {
if (keyCode == KeyEvent.KEYCODE_DELETE) {
// Handle delete.
return true;
}
if (keyCode == KeyEvent.KEYCODE_SPACE) {
// Handle space.
return true;
}
}
// Ignore all non-custom Events.
if (event.getAction() != KeyEvent.ACTION_MULTIPLE) {
return true;
}
if (keyCode == KeyEvent.KEYCODE_UNKNOWN) {
Log.e(TAG, event.toString());
// Pull out characters.
final String chars = event.getCharacters();
if (chars != null) {
// Do some stuff. This is never called!
}
}
return true;
}
However event.getCharacters()
never returns a non-null String! Is there something here that I'm missing? There is not much documentation governing the use of this specific KeyEvent constructor that I'm trying to manipulate to my own ends.
EDIT: It seems likely that the KeyEvent.writeToParcel(...) function does not parcel the character string, and so that data is lost when the KeyEvent is sent to the TextView.
I experimented with marshaling and unmarshaling a KeyEvent constructed in this way and in fact the string is no longer there. This behaviour is very strange. Does anyone know why this is?
...
KeyEvent ke = new KeyEvent(SystemClock.uptimeMillis(),
characterString, 0, KeyEvent.FLAG_CANCELED);
// Drop it into a parcel
Parcel p = Parcel.obtain();
ke.writeToParcel(p, 0);
// Get it out of this parcel.
KeyEvent kee = KeyEvent.CREATOR.createFromParcel(p);
Log.e(TAG, "unparcelled cstring: " + kee.getCharacters());
... (etc)
The last log statement always produces null.