Android Simulate Key Press

Android simulate key press

You can use instrumentation, ie following code called from onCreate of your activity will cause menu to be opened and closed multiple times:

    new Thread(new Runnable() {         
@Override
public void run() {
try {
Instrumentation inst = new Instrumentation();
for ( int i = 0; i < 10; ++i ) {
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_MENU);
Thread.sleep(2000);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
Thread.sleep(2000);
}
}
catch(InterruptedException e){
}
}
}).start();

...but I am not sure if this is what you are after

Simulate key press on an Android device

View.dispatchKeyEvent for example

Simulating Keyboard Events in Android

Actually, there is an easier method, that I found
Using Activity class or WebView class. Both have the same function.
The code looks something like this:

webView.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_1));

Android: How to trigger any key pressing event on soft keyboard?

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.

Simulating keypress in FMX application

You could checkout kbmFMX Pro which contains a virtual keyboard that will work with existing controls.

It is rather complex in Firemonkey to create a virtual keyboard and simulate key presses and involves getting access to TTextService and other features of Firemonkey.

If on Windows only, you can send windows messages to the window for key down and key up, but that is also relatively complex when simulating control/shift/alt keys.



Related Topics



Leave a reply



Submit