61

In Android, I need some code to "get text" and "set text" in the clipboard.

For example I want to put "asd" in memory and after that paste it from clipboard.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Lukap
  • 31,523
  • 64
  • 157
  • 244
  • Why are you trying to do this? As an Android user, I've never seen an app that does this. – Wesley Wiser Jul 11 '11 at 13:58
  • 1
    @Wesley for example keepass does this, to automatically clear the clipboard after some time. –  May 19 '15 at 21:47
  • 3
    `ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); if (clipboard != null && clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN)) { ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0); String yourText =item.getText().toString(); }` – Choletski May 23 '18 at 12:04

1 Answers1

90
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
clipboard.setText("Text to copy");
clipboard.getText();
Chirag
  • 56,621
  • 29
  • 151
  • 198
  • 2
    which package is ClipboardManager? android.cotent or android.text, hm and it seems to be deprecated – wutzebaer Jul 22 '13 at 16:37
  • 5
    @wutzebaer The ClipboardManager as used here is in [`android.text`](http://developer.android.com/reference/android/text/ClipboardManager.html). The newer interface is at [`android.content`](http://developer.android.com/reference/android/content/ClipboardManager.html) – Lekensteyn Sep 09 '13 at 15:33
  • 17
    Now **deprecated**! – Ujjwal Singh Dec 29 '14 at 09:38
  • 13
    **Since API 11** clipboard.setPrimaryClip(ClipData.newPlainText(text, text)); – Mats de Swart Feb 18 '15 at 01:46
  • 5
    Do this w/ the new API: ClipData clip = ClipData.newPlainText("message", msgText.getText()); clipboard.setPrimaryClip(clip); – kenyee Feb 26 '15 at 16:41
  • 1
    getText returns only the last copied data. How can I access all data from clipboard ? – partho Nov 03 '16 at 12:28