Last active
August 29, 2015 14:05
-
-
Save brandhill/666f8d64371ade54ddd8 to your computer and use it in GitHub Desktop.
android - avoid clipboard manager crash (only) on android 2.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Clipboard API has changed on level 11 of Android SDK. Here is some code to handle both versions from arinkverma. | |
// get text | |
@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; | |
} | |
// set text | |
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"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment