Wednesday, 3 August 2011

Android - turn key events into UTF8

As I've been asked a few times how to turn Android key events into UTF8 data, I figured it might be a good idea to share this info in my blog! It is actually really easy:

  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    int [] unicodePoints = new int[1];
    unicodePoints[0] = event.getUnicodeChar();
    String x = new String(unicodePoints, 0, 1);
    byte utf8Bytes[];
    try {
      utf8Bytes = x.getBytes("UTF-8");
      // Do something with your UTF-8 data here!
      // ....
      // ...
    } catch (UnsupportedEncodingException e) {
      Log.e(TAG, "Failed to key event to UTF8");
      Throw(e);
    }
    return true;
  }

No comments: