问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/35751231/android-how-to-trigger-any-key-pressing-event-on-soft-keyboard