Sergei Buvaka
Sergei Buvaka

Reputation: 621

null from Clipboard

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

Upvotes: 8

Views: 1493

Answers (1)

Nikolay Grebnev
Nikolay Grebnev

Reputation: 126

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

Upvotes: 11

Related Questions