Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy with clipboard manager that supports old and new android versions?

Tags:

java

android

I'm trying to copy text programatically on android, the most voted answer on another question provided these lines but when using them I get error: Class requires API level 11 (current min is 8):

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);

I copied the lines directly from the question. After trying with import android.content.ClipboardManager; I tested import android.text.ClipboardManager; and but it produced an error too The method setPrimaryClip(ClipData) is undefined for the type ClipboardManager plus warnings about ClipboardManager being deprecated.

My app that supports Android 2.2 (API 8 I think) onwards, how can I copy text so it works on all versions of android?

like image 872
lisovaccaro Avatar asked Jan 07 '13 03:01

lisovaccaro


1 Answers

Try to use something like the following:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    final android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) context
            .getSystemService(Context.CLIPBOARD_SERVICE);
    final android.content.ClipData clipData = android.content.ClipData
            .newPlainText("text label", "text to clip");
    clipboardManager.setPrimaryClip(clipData);
} else {
    final android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) context
            .getSystemService(Context.CLIPBOARD_SERVICE);
    clipboardManager.setText("text to clip");
}
like image 131
Raj Avatar answered Sep 21 '22 07:09

Raj