10

To get myself a little more familiar with content providers in Android, I'm making a small clipboard manager app. Its core functionality is to simply add whatever you copy to a database to display. I'm somewhat familiar with Android's Clipboard framework, but what I'm not sure how to do is to listen for copy "events" to know that a new item needs to be added to the clipboard.

To clarify, I need to be able to add a record to the database whenever the user copies something. How do I do this?

Tyler Treat
  • 14,640
  • 15
  • 80
  • 115

3 Answers3

10

If you are using API level 11 (3.0) or above, then you can use addPrimaryClipChangedListener which is documented here and there is some example usage here.

Eugene S
  • 3,092
  • 18
  • 34
  • 1
    Thanks. That kind of stinks that there's no solution for this for older APIs. – Tyler Treat Aug 03 '11 at 21:14
  • 1
    True, but if you're really desperate for it, you can try the suggestion below and just check the clipboard every so often (using a service). – Eugene S Aug 04 '11 at 03:40
  • 1
    Is this answer still valid for apps that are targeting Android 10 (api 29)? I have an app that has been using this method for the past few years to listen for clip events. Once I upgraded to api 29 it stopped working, and it seems like it might be related to Androids recent restrictions on foreground services. Wondering if you have any insights for this? – jwenz723 Sep 24 '19 at 07:10
  • @jwenz723 A service can't grab anything from the clipboardmanager when it's main app isn't in focus. This is how it works from Android Q (10). There is no workarounds as this has been deemed a security risk by Google. To clarify: You can't even get whatever is currently in the clipboard when your main app is out of focus. – Warpzit Oct 04 '19 at 07:57
8

Put inside your class:

ClipboardManager.OnPrimaryClipChangedListener mPrimaryChangeListener = new ClipboardManager.OnPrimaryClipChangedListener() {
        public void onPrimaryClipChanged() {

            // this will be called whenever you copy something to the clipboard
        }
    };

Put this inside onCreate method:

ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.addPrimaryClipChangedListener(mPrimaryChangeListener);

That's all. I hope I helped you.

Ayaz Alifov
  • 8,334
  • 4
  • 61
  • 56
2

What API do you have? This answer: Listener for clipboard content change? seems to suggest that there is a way for android 3.0 and higher, but not lower, unfortunately.

The only other thing I can think of is making a service, querying the clipboard every so often to see if it has changed or has new text. This can be easily done using ClipBoardManager.

Community
  • 1
  • 1
Otra
  • 8,108
  • 3
  • 34
  • 49