0

I was trying to copy to the clipboard when the app is closed, But it did not copy anything to the clipboard. I saw that android 10 restricted the access to the clipboard data to read in the background, is writing to the clipboard also restricted.

ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("copy", TEXT_FROM_SERVER);
clipboard.setPrimaryClip(clip);

this is the code, when something comes from the server even when the app is closed, I am calling this, but it's not working

Appreciate the suggestions. thanks

Zain
  • 37,492
  • 7
  • 60
  • 84
Manoj ahirwar
  • 1,062
  • 1
  • 10
  • 24
  • You didn't write any source code. So, it would be better if you enter source code. I don't know what's wrong without source code. –  Jan 08 '21 at 15:44
  • edited the post and added the code. – Manoj ahirwar Jan 08 '21 at 15:47
  • I am seeing any error in your source code. So, I will suggest you to check value of `TEXT_FROM_SERVER`. I think it is null. `Log.d("TEXT_FROM_SERVER",TEXT_FROM_SERVER);` –  Jan 08 '21 at 15:51
  • No, its not null. I am showing notification whatever the value of TEXT_FROM_SERVER. as I mentioned app is closed, I am suspecting maybe android is restricting access to clipboard when app is closed – Manoj ahirwar Jan 08 '21 at 15:55
  • No! You can copy whenever you want. I also tried it in my application. Are you adding it to `onDestroy()`? –  Jan 08 '21 at 15:57
  • I have to sure cause, there's only two way to call it while you are closing activity or application. `onDestroy()` and `onPause()`. If you are doing something else than I will request you to add further code. –  Jan 08 '21 at 15:58
  • No, I have a Firebase notification class that gets the data from my server. whenever it gets triggered from the server, it sends some TEXT value to the app. and shows that text in the notification. I am just calling the copy to clipboard code there. – Manoj ahirwar Jan 08 '21 at 15:59
  • 1
    Sorry! I am not getting any error. So, sorry. I can't help. <3 –  Jan 08 '21 at 16:00

1 Answers1

1

You're right, you cannot get access to the clipboard when the app in the background.
This is true for reading and writing. For more details, you may check ClipboardService#setPrimaryClip() method source code. The OS allows access only when ClipboardService#clipboardAccessAllowed() returns true.

sdex
  • 3,169
  • 15
  • 28