How to auto paste text or url in android application

Viewed 31

I want to implement a feature in my android app, when I copy some text or link from anywhere(from messages, whatsapp or instagram post link) in my phone and open my app, so I want the text to be auto pasted if text is in my clipboard.

Requirements:

  1. Open insta app & copy a post link
  2. Go back to my app and auto paste the copied link

if someone know about this then help me.

Thanks in advance.

1 Answers

I found the solution for auto pasting copied text on my App launch.

I added a button and when the button is clicked then I paste text from Clipboard.

We cannot use paste feature directly in onCreate(), so I automate the button click and set the button visibility to gone because I don't to show the button to the users.

So I added a Handler which is trigger after 2 seconds (2000 milliseconds) and inside the handler I added button.perforClick().

Below is the solution code.

public class MainActivity extends AppCompatActivity {

TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = findViewById(R.id.textView);
    Button button = findViewById(R.id.button);
    
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            button.performClick();
        }
    }, 2000);

    button.setOnClickListener(view -> {
        pasteText();
    });
}

private void pasteText() {
    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();

        textView.setText(pasteData);
        Log.i("PastedText", "text: " + pasteData);
    }
}
Related