Android copy/paste from clipboard manager

Damir picture Damir · Oct 4, 2013 · Viewed 48.8k times · Source

Is it possible to send past command so that it pastes text into currently focused edit text. Scenario:

  1. Background service listening for notification (done)
  2. When notification is received text needs to be copied to clipboard (done)
  3. Paste text to any currently focused field, if not possible just discard paste command.

I know how to copy text with ClipboardManager, but I don't know how to paste it.

Answer

Mukesh Kumar Singh picture Mukesh Kumar Singh · Oct 4, 2013

you can copy and paste text using following code :

  • for copy :

    ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
    ClipData clip = ClipData.newPlainText("your_text_to_be_copied");
    clipboard.setPrimaryClip(clip);
    
  • And paste it :

    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    String pasteData = "";
    
     // If it does contain data, decide if you can handle the data.
    if (!(clipboard.hasPrimaryClip())) {
    
    } else if (!(clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))) {
    
        // since the clipboard has data but it is not plain text
    
    } else {
    
        //since the clipboard contains plain text.
        ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
    
        // Gets the clipboard as text.
        pasteData = item.getText().toString(); 
    }
    

for more details check here