How to copy text programmatically in my Android app?
So everyone agree on how this should be done, but since no one want to give a complete solution, here goes:
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText("text to clip");
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("text label","text to clip");
clipboard.setPrimaryClip(clip);
}
I assume you have something like following declared in manifest:
<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="14" />
Use ClipboardManager#setPrimaryClip
method:
import android.content.ClipboardManager;
// ...
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", "Text to copy");
clipboard.setPrimaryClip(clip);
ClipboardManager
API reference
Googling brings you to android.content.ClipboardManager and you could decide, as I did, that Clipboard is not available on API < 11, because the documentation page says "Since: API Level 11".
There are actually two classes, second one extending the first - android.text.ClipboardManager and android.content.ClipboardManager.
android.text.ClipboardManager is existing since API 1, but it works only with text content.
android.content.ClipboardManager is the preferred way to work with clipboard, but it's not available on API Level < 11 (Honeycomb).
To get any of them you need the following code:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
But for API < 11 you have to import android.text.ClipboardManager
and for API >= 11 android.content.ClipboardManager