Reputation: 2142
I've implemented a copy from clipboard feature. So, whenever user copies something and my app is resumed after that I show a Snackbar to perform some action. It is working fine in Android 9 but in Android 10 as per policy changes it is not observing clipboard changes in background. That's ok but when I call following method in onResume it doesn't get any text as hasPrimaryClip is false. But on the same screen if I call same method on any button click then it is working fine and returning copied text. May be clipboard doesn't give access immediately after onResume and with some delay when any button is clicked it allows access. What could be the issue? Any ideas would be highly appreciable.
Thanks
public String readFromClipboard() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard.hasPrimaryClip()) {
android.content.ClipDescription description = clipboard.getPrimaryClipDescription();
android.content.ClipData data = clipboard.getPrimaryClip();
if (data != null && description != null && description.hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN))
return String.valueOf(data.getItemAt(0).getText());
}
return null;
}
Upvotes: 1
Views: 1266
Reputation: 2142
What I've observed is that we can access clipboard data in 'onWindowFocusChanged(boolean hasFocus)' method if hasFocus is true. This method is called approx. ~100ms later than onResume. So, copying by clicking on a button was working fine because app already had focus.
Upvotes: 3