Dr. K1NG Dr. K1NG - 21 days ago 12
Android Question

Pasting text from clipboard using a button across different apps (Android)

I tried finding something similar on the net, but couldn't. What I want, specifically, is the ability to have a button paste some text that originated in some other app rather than the one I'm making. So, say you copy some text from the "Google Chrome" app and go through the regular long tap and copy. Then, you open this app and press a button and it fetches the text from the clipboard and pastes it in a TextView. I understand that this isn't possible with the clipboard manager since all the examples I've seen show it as an object that stores information from within the app.

Answer

No, ClipboardManager is a system service, providing access to a device-wide clipboard.

Part of the reason why many examples might show both copying and pasting to the clipboard is so that the example is self-contained.

So, you get a ClipboardManager from getSystemService(), get the current contents via getPrimaryClip(), and use the ClipData as you see fit.

For example, this sample project contains two apps: drag/ and drop/. Mostly, this is to illustrate cross-app drag-and-drop operations on Android 7.0. But, drop/ supports a "Paste" action bar item (with associated keyboard shortcut), where I grab whatever is on the clipboard and, if it has a Uri, use it:

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.paste) {
      boolean handled=false;

      ClipData clip=
        getSystemService(ClipboardManager.class)
          .getPrimaryClip();

      if (clip!=null) {
        ClipData.Item clipItem=clip.getItemAt(0);

        if (clipItem!=null) {
          imageUri=clipItem.getUri();

          if (imageUri!=null) {
            showThumbnail();
            handled=true;
          }
        }
      }

      if (!handled) {
        Toast
          .makeText(this, "Could not paste an image!", Toast.LENGTH_LONG)
          .show();
      }

      return(handled);
    }

    return(super.onOptionsItemSelected(item));
  }

There is no code in this app to put stuff on the clipboard, though the associated drag/ app has code for that.

Comments