When I copy text to the clipboard onPrimaryClipChanged method is called twice. Any ideas why?
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
final ClipboardManager cliboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
cliboardManager
.addPrimaryClipChangedListener(new OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
ClipData clipData = cliboardManager.getPrimaryClip();
System.out
.println("********** clip changed, clipData: "
+ clipData.getItemAt(0));
}
});
return true;
}
Test case: Copying the text "continue" from the BBC web site will result in the following output:
continue
continue
But if I debug the program I can see that the clipData object has value:
ClipData { text/plain {T:continue } }
the first time onPrimaryClipChanged() is called and
ClipData { text/plain "BBC - Homepage" {T:continue } }
the next time onPrimaryClipChanged() is called.
So basically the first time ClipDescription is { text/plain } and the second time is ClipDescription { text/plain "BBC - Homepage" } (i.e including the title of the web page)
I meet this problem too, finally I know why it will call multi times!!!
Usually we
addPrimaryClipChangedListener()
, but we don'tremovePrimaryClipChangedListener()
.See: http://developer.android.com/reference/android/content/Context.html#CLIPBOARD_SERVICE
It means we should
removePrimaryClipChangedListener()
manually!My solution code :
// Prevention duplicate action of OnPrimaryClipChangedListener.
This is my workaround to prevent ClipboardManager OnPrimaryClipChangedListener is called twice for every copy.
I assume you didn't register multiple listeners, I can't say it is bug, you still you can workaround it. Try something like this: