Reputation: 11
I am working on an Android app where I use a sharing intent to share text. If the user copies the text instead of sharing it through an app, I want to detect when the clipboard content changes using ClipboardManager.OnPrimaryClipChangedListener.
However, on some devices, the onPrimaryClipChanged callback is not called when the text is copied from the share intent. This issue does not happen on all devices.
Here is the relevant code:
private void setClipBoardManager() {
ClipboardManager clipboardManager = (ClipboardManager) getApplicationContext().getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
@Override
public void onPrimaryClipChanged() {
try {
CharSequence copiedData = clipboardManager.getPrimaryClip().getItemAt(0).getText();
Log.d(TAG, "onPrimaryClipChanged: " + copiedData);
} catch (RuntimeException ex) {
Log.e(TAG, ex.getLocalizedMessage(), ex);
ex.printStackTrace();
}
}
});
}
public void share_text(String title, String subject, String text) {
int requestCode = 111;
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
sharingIntent.putExtra(Intent.EXTRA_TEXT, text);
PendingIntent pi = PendingIntent.getBroadcast(this, requestCode, new Intent(this, ShareBroadCast.class),
PendingIntent.FLAG_MUTABLE | PendingIntent.FLAG_UPDATE_CURRENT);
sharingIntent = Intent.createChooser(sharingIntent, title, pi.getIntentSender());
startActivity(sharingIntent);
}
I verified that the clipboard manager is properly initialized. onPrimaryClipChanged works fine in other scenarios outside of the sharing intent. The issue appears to be device-specific, but I’m not sure why.
It also this error in tag:ClipboardService
Denying clipboard access to package.name, application is not in focus neither is a system service for user 0
I expected onPrimaryClipChanged to be triggered whenever the user copies text from the share intent on all devices.
Upvotes: 1
Views: 36
Reputation: 101
You're seeing different behavior on different devices due to OEM customization of logic related to it. And I guess the behavior isn't tested by the Android Compatibility Suite, so a particular behavior isn't enforced.
An app is only supposed to be able to read the clipboard when it has focus. The sharesheet would take away focus, but the app would get it back when the sheet is dismissed after selecting the copy action. Seems like some devices have different behavior for either the focus change or the timing between the focus change and when the OnPrimaryClipChangedListener
is called.
On newer devices, you can use the new ChooserResult
API to check for CHOOSER_RESULT_COPY
. On older devices I think the only thing you can do if the Listener is not called is to check the Clipboard contents whenever your Activity resumes after invoking the sharesheet.
Upvotes: 0