0

Let's say we have the string String s= "Message from programmatic KeyboardPress". How do I send this string as keyboard output. For instance, a user currently focuses on a textfield and my string appears, since a keyboard output has been simulated.

Now, I don't want to set the text of a EditText object programmatically. I want to simulate a real keyboard input. I found how to do it in basic java (How to send keyboard outputs).

How does one realize this in android java?

Josip Domazet
  • 2,246
  • 2
  • 14
  • 37
  • 1
    Are you writing a keyboard? Use InputConnection.commitText(). Are you not the keyboard? There's no way to do this, on purpose for security reasons. – Gabe Sechan Aug 23 '19 at 20:05
  • No I don't have a open keyboard. Are you sure about this? Because I know some Android devices that are able to e.g. write strings as keyboard output or as BroadCastReceiver output. – Josip Domazet Aug 23 '19 at 20:11
  • I just realized they are only able to do that because a keyboard was open. Hmmmm.... Is there a way to get the currently open InputConnection? Thank you for your help btw. – Josip Domazet Aug 23 '19 at 20:15
  • The keyboard itself can write string output. An app could fake it to itself by calling editText.getInoutConnection().commit Text(). You can't fake it to another app at all – Gabe Sechan Aug 23 '19 at 20:19
  • :( Well thank you anyways! – Josip Domazet Aug 23 '19 at 20:20

1 Answers1

0

For future readers:

Gabe Sechan (Thanks!) pointed out that this isn't possible in android due to security restrictions. So what I came up with is to copy the string to the clipboard. It isn't as quick as directly simulating a keyboard output, but at least it works.

In my case, I needed to run the code outside of the main thread so I used this:

 runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ClipboardManager clipboard = (ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
                            ClipData clip = ClipData.newPlainText("message", s);
                            clipboard.setPrimaryClip(clip);
                        }
                    });

For more info on how to copy something to the clipboard take a look at this: How to Copy Text to Clip Board in Android?

Josip Domazet
  • 2,246
  • 2
  • 14
  • 37