There is a one-key imitation code:

public static void simulateKey(final int KeyCode) { new Thread() { @Override public void run() { try { Instrumentation inst = new Instrumentation(); inst.sendKeyDownUpSync(KeyCode); } catch (Exception e) { Log.e("Exception when sendKeyDownUpSync", e.toString()); } } }.start(); } 

Here is a list of all the buttons (KeyCode): Click to show

Call: simulateKey (KeyEvent.KEYCODE_F); It works correctly and accurately, simulates pressing "f".


BUT: How to simulate pressing 2 keys? I need instead: "f" output: "F".

But, the code of the capital letter is not and therefore it is necessary to press two at once: Shift + f

  • Call successively two presses SHIFT and then F? Ah, this is an android. Forget) - Serhii Dikobrazko
  • But you’ll enter big letters in Android, so I’ll always have time to “forget”!)) Can it be possible to click on "CAPS_LOCK" and "f" consistently? But it does not roll) - LEO
  • The question was resolved: KeyEvent downShiftF = new KeyEvent (mDownTime, mEventTime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_F, 5, KeyEvent.META_SHIFT_ON); inst.sendKeySync (downShiftF); - LEO
  • woesss! Right now I will prepare and publish. - LEO

2 answers 2

In the example (ApiDemos), "Hello" is written with a capital letter like this:

  // Act like the user is typing some text. sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT)); sendCharacterSync(KeyEvent.KEYCODE_H); sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_SHIFT_LEFT)); sendCharacterSync(KeyEvent.KEYCODE_E); sendCharacterSync(KeyEvent.KEYCODE_L); sendCharacterSync(KeyEvent.KEYCODE_L); sendCharacterSync(KeyEvent.KEYCODE_O); 

    The question was resolved as follows:

      public static void simulateKey(final int KeyCode) { new Thread() { @Override public void run() { try { mDownTime = SystemClock.uptimeMillis(); mEventTime = SystemClock.uptimeMillis(); Instrumentation inst = new Instrumentation(); inst.sendKeySync(new KeyEvent(mDownTime, mEventTime, KeyEvent.ACTION_DOWN, KeyCode, 5, KeyEvent.META_SHIFT_ON)); } catch (Exception e) { Log.e("Exception when sendKeySync", e.toString()); } } }.start(); }