Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access clipboard data in Android?

How do i get data from clip board. I want to get data and show in toast.Means In my android phone in any edit text .. When will long press and copy some string value .. That's should toast. How can i achieve this ?? In every tutorial i get, they copy from specify editText. I want like where ever in my phone i will copy some text .. I just need to get assess that particular string ... And clipboard.getText();also not working.

I tried

public class ClipBoardDataManager extends BroadcastReceiver {

        public ClipBoardDataManager() {
        }

        @Override
        public void onReceive(Context context, Intent intent) {

            String callNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

            ClipboardManager clipboard = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);

            ClipData myClip = ClipData.newPlainText("text", clipboard.getText());
            clipboard.setPrimaryClip(myClip);


            ClipData abc = clipboard.getPrimaryClip();
            ClipData.Item item = abc.getItemAt(0);

            Toast.makeText(ctx,item.toString(),Toast.LENGTH_SHORT).show();


        }
    }

and register.

IntentFilter intentFilter1 = new IntentFilter(String.valueOf(Intent.FILL_IN_CLIP_DATA));

ctx.registerReceiver(clipBoardDataManager,intentFilter1);

Still i am not getting it .. Please help!!!

like image 310
Tapan Patro Avatar asked Mar 15 '17 10:03

Tapan Patro


2 Answers

Java

ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener(new OnPrimaryClipChangedListener() {

    @Override
    public void onPrimaryClipChanged() {
        ClipData clipData = clipBoard.getPrimaryClip();
        ClipData.Item item = clipData.getItemAt(0);
        String text = item.getText().toString();

        // Access your context here using YourActivityName.this
    }
});

Kotlin

val clipBoardManager = context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
clipBoardManager.addPrimaryClipChangedListener {
    val copiedString = clipBoardManager.primaryClip?.getItemAt(0)?.text?.toString()
    // Your code
}

Hope this helps

like image 185
Zaki Pathan Avatar answered Oct 05 '22 13:10

Zaki Pathan


Kotlin

Clean, reusable, and simple working solution using Extension function -

fun Context.getFromClipBoard() : String? {
    val clipBoardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
    return clipBoardManager.primaryClip?.getItemAt(0)?.text?.toString()
}
like image 27
Dharamveer Mithilesh Gupta Avatar answered Oct 05 '22 12:10

Dharamveer Mithilesh Gupta