Android how to get string from onPrimaryClipChanged clipboard?

I am trying to get the text copied to the clipboard using the following listener:

import android.content.ClipboardManager.OnPrimaryClipChangedListener;
import com.orhanobut.logger.Logger;

public class ClipboardListener implements OnPrimaryClipChangedListener
{

    public void onPrimaryClipChanged()
    {
        // do something useful here with the clipboard
        // use getText() method
        Logger.d("Clipped");
    }
}

The listener is initialized as follows:

ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener( new ClipboardListener());

After copying the text to the clipboard onPrimaryClipChanged, but I do not know how to get the copied text in this method using ClipboardManager. getPrimaryClip () , because this method is not available from the context and is not passed in the parameter onPrimaryClipChanged.

+4
source share
1 answer

I would suggest adding a listener as follows instead of creating a new class. I have included how to get text from ClipData.

, , , , .

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
    }
});
+7

All Articles