I just discovered that this code goes to crash my app only on android 2.x
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(textView1.getText());
I think... I need add check android version before run this method, which is correct code to permit runs also on android 2.x?
Thanks!
Clipboard API has changed on level 11 of Android SDK. Here is some code to handle both versions from arinkverma.
I hope this can get into support library one day.
@SuppressWarnings("deprecation")
public void putText(String text){
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES. HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = ClipData.newPlainText("simple text",text);
clipboard.setPrimaryClip(clip);
}
}
@SuppressWarnings("deprecation")
public String getText(){
String text = null;
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES. HONEYCOMB ) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
text = clipboard.getText().toString();
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
text = clipboard.getText().toString();
}
return text;
}
Thanks Snicolas giving reference. I hope this will solve the problem. Also remember to include the library of both api level, else you will get error on build.
The build target has been set to Api 7 to 15, preferably 10
Preview of Manifest file
<uses-sdk android:maxsdkversion="15" android:minsdkversion="7" android:targetsdkversion="10"></uses-sdk>
The version of Snicolas are very nice.
But the else part of getText() has a error.
A full version is:
@SuppressWarnings("deprecation")
public String getText(Activity a){
String text = null;
int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB ) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) a.getSystemService(Context.CLIPBOARD_SERVICE);
text = clipboard.getText().toString();
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) a.getSystemService(Context.CLIPBOARD_SERVICE);
text = clipboard.getPrimaryClip().getItemAt(0).getText().toString();
}
return text;
}