The CommonsBlog


Developer PSA: Please Fix Your Clipboard Handling

AndroidPolice reported on a fairly unpleasant bug in Android 4.3. Until such time as a fix is rolled out in a patch release, developers should add some more smarts to the clipboard handling in their projects.

What the Bug Is

The bug stems from the clipboard monitoring behaviors added to ClipboardManager in API Level 11, combined with the App Ops stuff that I blogged about earlier.

If an app has used addPrimaryClipChangedListener(), any other app that tries to paste to the clipboard will crash.

The first crash will be a SecurityException:

java.lang.SecurityException: uid ... does not have android.permission.UPDATE_APP_OPS_STATS

The second and subsequent times this occurs on the device, it will be an IllegalStateException:

java.lang.IllegalStateException: beginBroadcast() called while already in a broadcast

The only resolution is to unregister the clipboard listener… and hope that the first crash has not occurred. If it has, a full reboot of the device is required to fix the broken system.

If Your App Monitors the Clipboard…

In principle, if you only monitor the clipboard in the foreground, register for it in onResume() and remove it in onPause().

In practice, you are probably not monitoring the clipboard in the foreground, as you would be the only likely one to be putting anything in the clipboard at that point.

If you have a long-running service that is monitoring the clipboard, please ensure that the users have an easy way to stop that behavior, even if it means stopping your whole service. Yes, this may mean that your app has seriously degraded functionality. However, the alternative is that the user has to keep rebooting their device while your app is installed, and if they have to remove your app, they might well elect to put some choice comments in the Play Store as well.

If Your App Pastes to the Clipboard…

If you are pasting to the clipboard, with setPrimaryClip() or the older setText(), you will want to throw a try/catch block around those calls, so you catch the RuntimeExceptions that will be thrown.

However, you will need to tell your users that they are now fairly well screwed, needing to both find the clipboard-monitoring app and learn how to control it (or uninstall/disable it, if needed), plus reboot their device, in order to paste to the clipboard again.

IOW, even though your app has not done anything wrong, you have to be the bearer of the bad news.


The Busy Coder’s Guide to Android Development: the most Android knowledge allowed by law! :-)