redrom redrom - 5 months ago 15
Android Question

Android how to get string from clipboard onPrimaryClipChanged?

I trying to get text copied into 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");
}
}


Listener is initialized using the:

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


After the text is copied into clipboard onPrimaryClipChanged is fired, but i don't know how to get the copied text in this method using the getPrimaryClip (based on the docs https://developer.android.com/reference/android/content/ClipboardManager.html#getPrimaryClip())

Because following method is not available from the context and is not passed in param of the onPrimaryClipChanged.

How can i solve it please?

Many thanks from any advice.

Answer

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

You mention being unable to access your context in the listener, I've added a comment within the code below showing how to do so.

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