Search code examples
javaandroidandroid-notificationsclipboard

How to know whether any link was copied even when the app is closed?


Currently making a URL shortener, I wanted to add functionality to show a notification when a URL was copied even when the app is in the background or closed.

Using a service class can be a good idea but it has some disadvantages:

  1. Some devices like MI and OnePlus don't allow running services for more than 30 seconds.

  2. We need to always show a notification otherwise the service doesn't run for long

  3. etc...

I currently used this in my app and added some copyable content on the app and it worked:

class ClipboardListener implements ClipboardManager.OnPrimaryClipChangedListener
{
   public void onPrimaryClipChanged()
   {
      Log.i("currenltyCopiedText - ", getPrimaryClip() + "");
   }
}

ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener( new ClipboardListener() );

But, this works only IN the app. Not when it is closed. How can I achieve that?


Solution

  • You can't, at least starting Android 10 (so at least half of used devices worldwide at this moment). Privacy/security reasons ofc

    from DOC:

    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.

    in short: "has focus" means any of your Activity is on foreground/visible. Your code may probably work even in Service (or ForegroundService), but only when any Activity is on screen