1

I am trying to create a widget which takes an input of serial key from users. I also added a paste button for convenience because serial key is 14 digits long. Below code was working fine for devices before android 10

ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);
String serial = item.getText();

Then I compare serial with our serial regex. Issue is, Current snippet returns null value for android 10.

Following limitation, I found on official documentation.

Limited access to clipboard data.

Unless your app is the default input method editor (IME) or is the app that currently has focus, your app cannot access clipboard data on Android 10 or higher.

Is there any way I can enable focus when button on the widget is pressed? Thanks in advance.

Deep Dave
  • 159
  • 1
  • 8

1 Answers1

0

Your window should be focused when accessing Clipboard:

override fun onWindowFocusChanged(hasFocus: Boolean) {
    super.onWindowFocusChanged(hasFocus)
    if(hasFocus){
        val clipboard =
            getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        val item: ClipData.Item = clipboard.primaryClip.getItemAt(0)
        val serial: String = item.text.toString()
    }
}

This should work inside your activity.

Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
  • Thank you for a quick reply. I want to perform paste operation in my widget which is located on the device's home screen, – Deep Dave Jun 03 '20 at 11:14