Search code examples
androidkotlincopylistenerclipboard

How to avoid copy-listener reacts on paste in Android?


I want to run a Toast message in my app when the user copies something to the clipboard. That's why I implemented such a listener in my activity:

class MainActivity : AppCompatActivity() {
    var mPrimaryChangeListener = OnPrimaryClipChangedListener {
    Toast.makeText(applicationContext, "You have copied something!", LENGTH_SHORT).show()
}
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // ...
        val clipboard = this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        clipboard.addPrimaryClipChangedListener(mPrimaryChangeListener)
    }

// ...
}

The problem is that the Toast shows also when some text is pasted from clipboard and I want this to happen only if the user copies a text. How can I solve this?


Solution

  • I tried your example with an emulator and it worked as you expected it to work.
    The documentation says the following:

    Callback that is invoked by ClipboardManager when the primary clip changes.

    If this doesn't work on your test device you could try to save the clipboard string once your callback is triggered and the next time compare it with the clipboard at that time. If the two strings are the same that means that the user either pasted the text of the clipboard or just copied the same text again.
    You could then just show the toast if the two strings differ.