Copying and pasting from and to the system clipboard. Assuming text and/or html content.
Copy
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public static boolean copyToClipboard(Context context, String text) {
try {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText(
context.getResources().getString(
R.string.message), text);
clipboard.setPrimaryClip(clip);
}
return true;
} catch (Exception e) {
return false;
}
}
Paste
@SuppressLint("NewApi")
@SupressWarnings("deprecation")
public static String paste(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard.hasText()) {
return (String) clipboard.getText();
}
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard.hasPrimaryClip()
&& clipboard.getPrimaryClipDescription().hasMimeType("text/plain")) {
ClipData clip = clipboard.getPrimaryClip();
return clip.toString();
}
}
return null;
}