使用ClipboardUtils兼容API LEVEL 11以下实现复杂粘贴

实现功能:复杂粘贴内容 问题描述:android.content.ClipboardManager在APILevel 11之后才可以使用,而我们目前还要兼容API Level 10(2.3.3)

解决办法:编写了一个工具类来完成这个工作“ClipboardUtils”。

VIEW SOURCE

public class ClipboardUtils {
    private static ClipboardManager mClipboardManager;
    private static android.content.ClipboardManager mNewCliboardManager;

    private static void instance(Context context) {
        if (SDK_INT >= HONEYCOMB) {
            if (mNewCliboardManager == null)
                mNewCliboardManager = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        } else {
            if (mClipboardManager == null)
                mClipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        }
    }

    /**
     * 为剪切板设置内容
     * 
     * @param context
     * @param text
     */
    public static void setText(Context context, CharSequence text) {
        if (SDK_INT >= HONEYCOMB) {
            instance(context);
            // Creates a new text clip to put on the clipboard
            ClipData clip = ClipData.newPlainText("simple text", text);

            // Set the clipboard's primary clip.
            mNewCliboardManager.setPrimaryClip(clip);
        } else {
            instance(context);
            mClipboardManager.setText(text);
        }
    }

    /**
     * 获取剪切板的内容
     * 
     * @param context
     * @return
     */
    public static CharSequence getText(Context context) {
        StringBuilder sb = new StringBuilder();
        if (SDK_INT >= HONEYCOMB) {
            instance(context);
            if (!mNewCliboardManager.hasPrimaryClip()) {
                Log.d("android.content.ClipboardManager", "Clipboard is empty");
                return sb.toString();
            } else {
                ClipData clipData = (mNewCliboardManager).getPrimaryClip();
                int count = clipData.getItemCount();

                for (int i = 0; i < count; ++i) {

                    ClipData.Item item = clipData.getItemAt(i);
                    CharSequence str = item.coerceToText(context);
                    Log.i("mengdd", "item : " + i + ": " + str);
                    sb.append(str);
                }
            }

        } else {
            instance(context);
            sb.append(mClipboardManager.getText());
        }
        return sb.toString();
    }
}

 

思路:判断当前SDK版本,11以下使用android.text.ClipboardManager,否则采用android.content.ClipboardManager。

posted @ 2015-07-07 10:07  Atlas's blog  阅读(778)  评论(0编辑  收藏  举报