Skip to content

Instantly share code, notes, and snippets.

@DHuckaby
Created October 19, 2012 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DHuckaby/3919966 to your computer and use it in GitHub Desktop.
Save DHuckaby/3919966 to your computer and use it in GitHub Desktop.
Forwards compatible version of the ClipboardManager for preserving the api on new versions of the os.
public class ClipboardManagerCompat {
public static ClipboardManager getInstance(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return new DeprecatedClipboardManager(context);
} else {
return new HoneycombClipboardManager(context);
}
}
@SuppressWarnings("deprecation")
private static class DeprecatedClipboardManager implements ClipboardManager {
private android.text.ClipboardManager mClipboardManager;
public DeprecatedClipboardManager(Context context) {
mClipboardManager = (android.text.ClipboardManager) context.getSystemService(android.content.Context.CLIPBOARD_SERVICE);
}
@Override
public void setText(CharSequence text) {
mClipboardManager.setText(text);
}
@Override
public CharSequence getText() {
return mClipboardManager.getText();
}
@Override
public boolean hasText() {
return mClipboardManager.hasText();
}
}
@TargetApi(11)
private static class HoneycombClipboardManager implements ClipboardManager {
private android.content.ClipboardManager mClipboardManager;
private static CharSequence mText = new String();
public HoneycombClipboardManager(Context context) {
mClipboardManager = (android.content.ClipboardManager) context.getSystemService(android.content.Context.CLIPBOARD_SERVICE);
}
@Override
public void setText(CharSequence text) {
if (text != null) {
synchronized (mText) {
mText = text;
mClipboardManager.setPrimaryClip(android.content.ClipData.newPlainText(android.content.ClipDescription.MIMETYPE_TEXT_PLAIN, mText));
}
}
}
@Override
public CharSequence getText() {
synchronized (mText) {
return mText;
}
}
@Override
public boolean hasText() {
synchronized (mText) {
return mText.length() > 0;
}
}
}
/**
* Interface to the clipboard service, for placing and retrieving text in
* the global clipboard.
*
* <p>
* You do not instantiate this class directly; instead, retrieve it through
* {@link ClipboardManagerCompat#getInstance(Context)}.
*/
public static interface ClipboardManager {
/**
* Returns the text on the clipboard. It will eventually be possible to
* store types other than text too, in which case this will return null
* if the type cannot be coerced to text.
*/
public abstract CharSequence getText();
/**
* Sets the contents of the clipboard to the specified text.
*/
public abstract void setText(CharSequence text);
/**
* Returns true if the clipboard contains text; false otherwise.
*/
public abstract boolean hasText();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment