salvob
salvob

Reputation: 1370

How to detect a "copy to clipboard" event

I would like to detect the event of "copy to clipboard", so when a user, after having selected a string or url, tap on copy to clipboard.

Do you have any idea how to check this in an Android environment?

Upvotes: 3

Views: 7783

Answers (2)

Cristan
Cristan

Reputation: 14105

ClipboardManager.addPrimaryClipChangedListener and ClipboardManager.getText() are deprecated. New solution:

val clipboardManager = context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
clipboardManager.addPrimaryClipChangedListener {
    val clipboardAsText = clipboardManager.primaryClip?.getItemAt(0)?.text
    if (clipboardAsText != null) {
        Toast.makeText(context, "Text in clipboard: $clipboardAsText", Toast.LENGTH_SHORT).show()
    }
}

Upvotes: 2

You are looking for http://developer.android.com/reference/android/content/ClipboardManager.html

ClipboardManager
.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
  @Override
  protected void onPrimaryClipChanged() {
    Log.i("clipboard", "changed to:" + ClipboardManager.getText());
  }
});

Upvotes: 6

Related Questions