4

I want to implement a listener which will listen if some copied any thing from any application.

I heard about ClipboardManager.OnPrimaryClipChangedListener() which will listen copy action, but this is not a Receiver (As I understand). I got a sample application, logic behind this application is, start service from system boot and run a service which will listen Copy action, but I think this will drain the battery. Am I right?

So how can I implement a Broadcast receiver which can listen Copy action.

Sergey K.
  • 24,894
  • 13
  • 106
  • 174
Android Learner
  • 2,559
  • 6
  • 34
  • 43

1 Answers1

12

Here is the listener:

class ClipboardListener implements ClipboardManager.OnPrimaryClipChangedListener
{
   public void onPrimaryClipChanged()
   {
      // do something useful here with the clipboard
      // use getText() method
   }
}

Just register it:

ClipboardManager clipBoard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
clipBoard.addPrimaryClipChangedListener( new ClipboardListener() );
Sergey K.
  • 24,894
  • 13
  • 106
  • 174
  • Is this listen from background too? like if I added this listener in my application, user run my app, and then switches to another app(my app will go in background), then this listner will be capable to listen if user perform copy in other app? – Android Learner Jul 16 '12 at 09:26
  • 1
    Yes, this will listen in the background for clipboard changes (but you have to ensure that your app is running if the user switches to another). Once the listener is invoked get the data from the clipboard and do what you want. – Sergey K. Jul 16 '12 at 09:28
  • One more question (I am sorry for that), This will act as same as Broadcast receiver, like they works in background until user kills the application? Or this will work until Android OS kills the application from memory due to memory sortage? – Android Learner Jul 16 '12 at 09:35
  • 1
    This works until OS kills the applications from memory. Create a service if you would like to simulate Broadcast receiver behavior. – Sergey K. Jul 16 '12 at 09:37
  • Can you give me the idea pliz? – Android Learner Jul 16 '12 at 09:40
  • Use Service instead of Activity http://developer.android.com/reference/android/app/Service.html – Sergey K. Jul 16 '12 at 09:41
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/13923/discussion-between-android-learner-and-sergey-k) – Android Learner Jul 16 '12 at 09:43
  • @SergeyK. How to make this work if my app is not running in background? – Anuj Garg Jul 25 '17 at 07:28
  • @AnujGarg: you can go with a Service running in the background, so that clipboard handling can be decoupled from your app (which might be too heavy to be always running in the background). – Sergey K. Jul 25 '17 at 23:16