5

I need to get copied data from clipboard. I use this code:

val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
val clipData: ClipData? = clipboardManager.primaryClip
clipData?.let { textView.text = clipData.getItemAt(0).text }

If I use this code inside onCreate() or onResume() callbacks, I always getting null from clipboard.

But if I call this code:

textView.post {
        val clipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        val clipData: ClipData? = clipboardManager.primaryClip
        clipData?.let { textView.text = clipData.getItemAt(0).text }
}

I get copied string.

So, I make conclusion, that Clipboard waits until all views are rendered.

Why clipboard needs to wait for rendering all views? Or maybe clipboard is waiting for something else

Sergei Buvaka
  • 551
  • 1
  • 5
  • 16
  • Maybe [this resource](https://stackoverflow.com/a/33161782/10854225) can help, at the moment I can not test it, but I hope that this can help – vincenzopalazzo Dec 27 '20 at 12:03

1 Answers1

6

It is happening because your app should be in focus when you try to get primaryClip from Clipboard.

All views have to be set up and tied to activity, that's why you have to add your function to UI queue with help of view.post { }

That change was added in API 29 https://developer.android.com/about/versions/10/privacy/changes#clipboard-data

  • Thank you for this valuable context. I was trying to understand why I couldn't get the clipboard data on the onResume. The clipboard primaryClip is null always for some reason - but putting my logic inside a `post` worked. Great stuff! – Guimo Apr 29 '22 at 18:14
  • Follow up on this, found a great explanation on where to best use the Clipboard code - inside `onWindowsFocusChanged` worked for me. More details [here](https://medium.com/@fergaral/working-with-clipboard-data-on-android-10-f641bc4b6a31). I was getting an error saying `ClipboardService` couldn't be called and using that callback on my `Activity` did the trick – Guimo May 02 '22 at 09:43