30

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.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Damir
  • 1,092
  • 4
  • 18
  • 32
  • #important: For Android 10 and higher follow this : https://medium.com/@fergaral/working-with-clipboard-data-on-android-10-f641bc4b6a31 – pravingaikwad07 Apr 10 '21 at 17:55

8 Answers8

51

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

MHSaffari
  • 858
  • 1
  • 16
  • 39
Mukesh Kumar Singh
  • 4,512
  • 2
  • 22
  • 30
  • 1
    what is the difference between `getSystemService(Context.CLIPBOARD_SERVICE)` and `getSystemService(CLIPBOARD_SERVICE)` @mukesh-kumar – Sp4Rx Nov 01 '16 at 07:15
  • 3
    @Sp4Rx, There is difference between `getSystemService(Context.CLIPBOARD_SERVICE)` and `getSystemService(CLIPBOARD_SERVICE)`. Actually `CLIPBOARD_SERVICE` is defined in `Context` class as a `public static` so you can access it `Context.CLIPBOARD_SERVICE`. As `Activity` class extends the `Context` so you can access it `CLIPBOARD_SERVICE` as well. – Mukesh Kumar Singh Nov 02 '16 at 12:40
  • Thanks for this clarification @mukesh-kumar – Sp4Rx Nov 02 '16 at 17:43
  • Btw if you didn't know, it's ClipDescription.MIMETYPE_TEXT_PLAIN – larsaars Dec 02 '19 at 20:58
  • It's interesting that you use else section to run the code, but not prior to if statement. Also on the first if statement I add this Toast to alert the user what's going on by the mistake: Toast.makeText(getApplicationContext(),"The copied item should be a plain text not an image or video. Please try with another copied item.",Toast.LENGTH_SHORT).show(); – Bay Jan 02 '21 at 12:19
  • alone `description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)` didn't work for me on mi phone i had to add `hasMimeType(MIMETYPE_TEXT_HTML)` as well – beginner Jul 06 '21 at 11:46
19

If you just want to "copy and paste" some code into your app, you can use the following.

#Copy

String textToCopy = etCodeWindow.getText().toString();

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText(null, textToCopy);
if (clipboard == null) return;
clipboard.setPrimaryClip(clip);

#Paste

Get the text to paste

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard == null) return;
ClipData clip = clipboard.getPrimaryClip();
if (clip == null) return;
ClipData.Item item = clip.getItemAt(0);
if (item == null) return;
CharSequence textToPaste = item.getText();
if (textToPaste == null) return;

or

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
try {
    CharSequence textToPaste = clipboard.getPrimaryClip().getItemAt(0).getText();
} catch (Exception e) {
    return;
}

or the same in Kotlin:

val clipboard = (getSystemService(Context.CLIPBOARD_SERVICE)) as? ClipboardManager
val textToPaste = clipboard?.primaryClip?.getItemAt(0)?.text ?: return false

Inserting it at the cursor position

If there is a selection then the selection will be replaced with the paste text.

int start = Math.max(myEditText.getSelectionStart(), 0);
int end = Math.max(myEditText.getSelectionEnd(), 0);
myEditText.getText().replace(Math.min(start, end), Math.max(start, end),
            textToPaste, 0, textToPaste.length());

#Notes

  • This answer assumes that you are no longer supporting pre-API 11. If you are then see the edit history.
  • Import android.content.ClipboardManager and android.content.ClipData.
  • I used to just get the paste text in a one liner until I discovered that ClipData was giving a NPE crash sometimes. Now I would either use a try/catch block or check more carefully for nulls.
Tuan Chau
  • 1,243
  • 1
  • 16
  • 30
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 1
    +1 Your code works like a charm, and for those who want to copy the text from a textview then make `textview.setTextIsSelectable(true)` and then use the code of the author. – Andritchi Alexei May 29 '19 at 08:48
  • worked well in Kotlin. Will update if I face any issue. thanks a lot mate :) – Darshn May 05 '20 at 19:33
11

a short summary of above after honeycomb >= API 13:

public String readFromClipboard() {
    ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    if (clipboard.hasPrimaryClip()) {
        android.content.ClipDescription description = clipboard.getPrimaryClipDescription();
        android.content.ClipData data = clipboard.getPrimaryClip();
        if (data != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) 
            return String.valueOf(data.getItemAt(0).getText());
    }
    return null;
}
tom nobleman
  • 366
  • 3
  • 8
5

I do it this way. Clipboard manager for all api levels.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.util.Log;


public class MyClipboardManager {

    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public boolean copyToClipboard(Context context, String text) {
        try {
            int sdk = android.os.Build.VERSION.SDK_INT;
            if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                        .getSystemService(context.CLIPBOARD_SERVICE);
                clipboard.setText(text);
            } else {
                android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
                        .getSystemService(context.CLIPBOARD_SERVICE);
                android.content.ClipData clip = android.content.ClipData
                        .newPlainText(
                                context.getResources().getString(
                                        R.string.message), text);
                clipboard.setPrimaryClip(clip);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @SuppressLint("NewApi")
    public String readFromClipboard(Context context) {
        int sdk = android.os.Build.VERSION.SDK_INT;
        if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
                    .getSystemService(context.CLIPBOARD_SERVICE);
            return clipboard.getText().toString();
        } else {
            ClipboardManager clipboard = (ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);

            // Gets a content resolver instance
            ContentResolver cr = context.getContentResolver();

            // Gets the clipboard data from the clipboard
            ClipData clip = clipboard.getPrimaryClip();
            if (clip != null) {

                String text = null;
                String title = null;

                // Gets the first item from the clipboard data
                ClipData.Item item = clip.getItemAt(0);

                // Tries to get the item's contents as a URI pointing to a note
                Uri uri = item.getUri();

                // If the contents of the clipboard wasn't a reference to a
                // note, then
                // this converts whatever it is to text.
                if (text == null) {
                    text = coerceToText(context, item).toString();
                }

                return text;
            }
        }
        return "";
    }

    @SuppressLint("NewApi")
    public CharSequence coerceToText(Context context, ClipData.Item item) {
        // If this Item has an explicit textual value, simply return that.
        CharSequence text = item.getText();
        if (text != null) {
            return text;
        }

        // If this Item has a URI value, try using that.
        Uri uri = item.getUri();
        if (uri != null) {

            // First see if the URI can be opened as a plain text stream
            // (of any sub-type). If so, this is the best textual
            // representation for it.
            FileInputStream stream = null;
            try {
                // Ask for a stream of the desired type.
                AssetFileDescriptor descr = context.getContentResolver()
                        .openTypedAssetFileDescriptor(uri, "text/*", null);
                stream = descr.createInputStream();
                InputStreamReader reader = new InputStreamReader(stream,
                        "UTF-8");

                // Got it... copy the stream into a local string and return it.
                StringBuilder builder = new StringBuilder(128);
                char[] buffer = new char[8192];
                int len;
                while ((len = reader.read(buffer)) > 0) {
                    builder.append(buffer, 0, len);
                }
                return builder.toString();

            } catch (FileNotFoundException e) {
                // Unable to open content URI as text... not really an
                // error, just something to ignore.

            } catch (IOException e) {
                // Something bad has happened.
                Log.w("ClippedData", "Failure loading text", e);
                return e.toString();

            } finally {
                if (stream != null) {
                    try {
                        stream.close();
                    } catch (IOException e) {
                    }
                }
            }

            // If we couldn't open the URI as a stream, then the URI itself
            // probably serves fairly well as a textual representation.
            return uri.toString();
        }

        // Finally, if all we have is an Intent, then we can just turn that
        // into text. Not the most user-friendly thing, but it's something.
        Intent intent = item.getIntent();
        if (intent != null) {
            return intent.toUri(Intent.URI_INTENT_SCHEME);
        }

        // Shouldn't get here, but just in case...
        return "";
    }

}
A.S.
  • 4,574
  • 3
  • 26
  • 43
  • All these answers show how to write/read to/from clipboard, but I need to simulate paste command into currently focused edit text in any application (for example into web browser) not only into my app. – Damir Oct 04 '13 at 10:19
  • @Damir On which event do you want to copy the text frpom the clipboard to your EditText? – A.S. Oct 04 '13 at 10:24
  • I want to copy text as soon as it appears on clipboard. I actually have Bluetooth device which scannes bar code and sends bar code number to my android device. I want to past that bar code to any possible field, if not possible just discard it. I assume that "Paste" action is integrated into Android and I just want to simulate it. – Damir Oct 04 '13 at 10:28
  • Hmm... just have a look for custom Intents in Android. or look at that approach http://stackoverflow.com/questions/4913154/passing-data-from-a-broadcastreceiver-to-mainactivity-works-correctly-only-once – A.S. Oct 04 '13 at 10:33
  • If I understand correctly I can use custom intents but in my own application not globally in OS, so this is also not solution. I need to paste received text into any application which has edit text focused. – Damir Oct 04 '13 at 10:40
  • There is an app bluepiano which scannes bar code and paste it to any edit text, you can see it for example. This is exactly what I need. – Damir Oct 04 '13 at 12:47
2
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
String copyedText = clipboard.getText();
Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75
  • 4
    Note that `clipboard.getText()` was deprecated in API level 11. `getPrimaryClip()` should be used instead. – t0thkr1s Feb 27 '18 at 09:38
1

It's an addendum to @Suragch 's answer.

In Kotlin:

        val clipboard = (getSystemService(Context.CLIPBOARD_SERVICE)) as? ClipboardManager
        val textToPaste = clipboard?.primaryClip?.getItemAt(0)?.text ?: return

        binding.<your paste button camelCase id>.setOnClickListener {
            if (clipboard.hasPrimaryClip()) {
                binding.<your EditText camelCase id>.setText(textToPaste)
            }
        }

Inside Fragment: getSystemService() is a method on the Context class and it's necesary to call Context first. It's possible by either using getContext() or alternatively, the getActivity() - Activity is also a Context.

this.activity.getSystemService(...)
this.context.getSystemService(...)

Or:

activity.getSystemService(...)
context.getSystemService(...)

Plus remember about only safe (?.) or non-null asserted (!!.) calls. If you don't want allow the user faste any data you can specify it, f.e:

if (clipboard.hasPrimaryClip() && textToPaste.isDigitsOnly())
Ozzini
  • 145
  • 1
  • 7
0

For best and easy way to copy paste programmatically is...

Create a Button and copy this code in onclicklistener.

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 

For Copy

clipboard.setText("which you want to copy"); 

For paste

textview1.setText(clipboard.getText().toString()); 
Antor
  • 9
  • 3
0

For most Android devices, above Honeycomb Android version 3.0 the below code will work

For copying text to Clipboard

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
        ClipData clip = android.content.ClipData
                    .newPlainText("copyingToClipboard", "your text here to be copied to clipboard");
    clipboard.setPrimaryClip(clip);

For Copying from Clipboard

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard.hasPrimaryClip() && (clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_PLAIN) || clipboard.getPrimaryClipDescription().hasMimeType(MIMETYPE_TEXT_HTML))) {
            ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
            String clipboardtext = item.getText().toString();
            Toast.makeText(Context,clipboardtext,Toast.LENGTH_LONG).show();
        }

The code will avoid null value exception in case the clipboard doesn't contain any data.

Dharaneshvar
  • 1,348
  • 1
  • 6
  • 12