5

Is there any way to press key of Android Soft Keyboard programmatically.

Like: When keyboard will appear, I want to press "J" key through my code not from fingers.

Mohit Chauhan
  • 455
  • 1
  • 10
  • 20

1 Answers1

4

First method:

IBinder binder = ServiceManager.getService("window"); 
IWindowManager manager = IWindowManager.Stub.asInterface(binder);
manager.injectKeyEvent(new KeyEvent(KeyEvent.yourAction, KeyEvent.yourKeyCode),true);

You can see more details here. There is another method in this link too.

Second method, using instrumentation:

Instrumentation inst = new Instrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);

And you can see this question that explains how to use instrumentation and webview to do that.

You don't need the keyboard to do this, you can show it or not.

A list of keyCodes if you want.

This link will show keyCode for every key that you press, I think it works with the android and linux keyboards, but don't know if the code will be the same using another OS.

Community
  • 1
  • 1
Ricardo A.
  • 685
  • 2
  • 8
  • 35
  • Thanks man! It works perfectly. Can you tell me what is the KeyCode for "?123" on the Android's Soft Keyboard? – Mohit Chauhan Mar 03 '16 at 15:39
  • I think is 63, and the constant KEYCODE_SYM. – Ricardo A. Mar 03 '16 at 17:10
  • Thanks for your reply. But it's not. Constant KEYCODE_SYM will shows an option to change keyboard. I have tried many constants but none of one can able to switch from alphabet keyboard view to numeric with symbols keyboard view. So, I still need that constant which will trigger key press event for "?123". – Mohit Chauhan Mar 04 '16 at 07:11
  • http://stackoverflow.com/a/9292485/1237175. Here they say ServiceManager class is hidden... There is no way i can use it ? – Ramesh_D Apr 03 '17 at 06:04
  • what about mimicing the ENTER key to be pressed while we're inside another openend activity (of other app) is it possible? – gumuruh Jul 31 '18 at 10:42
  • Note that second method cannot be from the main thread. you must do it from background thread. – Saman Sattari Dec 29 '19 at 10:23
  • The second method seems to only work for system apps. I got the error `java.lang.SecurityException: Injecting to another application requires INJECT_EVENTS permission` even after adding the permission to the manifest. – Sam Feb 28 '21 at 02:46