使用ClipboardUtils兼容API LEVEL 11如下實現複雜粘貼

實現功能:複雜粘貼內容 問題描述:android.content.ClipboardManager在APILevel 11以後纔可使用,而咱們目前還要兼容API Level 10(2.3.3)android

解決辦法:編寫了一個工具類來完成這個工做「ClipboardUtils」。app

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。ui

相關文章
相關標籤/搜索