Android系统剪切板

Android系统剪贴板


复制字符串到系统剪切板

/**
 * 复制文本到剪切板
 * 
 * @param text
 * @return
 */
@SuppressWarnings("deprecation")
public boolean copyStringToSystem(String text) {
    try {
        if (android.os.Build.VERSION.SDK_INT > 11) {
            android.content.ClipboardManager c = (android.content.ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
            c.setText(text);
        } else {
            android.text.ClipboardManager c = (android.text.ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
            c.setText(text);
        }
    } catch (Exception e) {
        return false;
    }
    return true;
}

获取系统剪贴板内容

/**
 * 获取剪切板数据
 * 
 * @return
 */
@SuppressWarnings("deprecation")
public String pasteStringFromSystem() {
    String clipResult = null;
    if (android.os.Build.VERSION.SDK_INT > 11) {
        android.content.ClipboardManager c = (android.content.ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData primaryClip = c.getPrimaryClip();
        Item itemAt = null;
        if (primaryClip != null) {
            itemAt = primaryClip.getItemAt(0);
        }
        if (itemAt != null) {
            String trim = itemAt.getText().toString().trim();
            clipResult = trim;
        }
    } else {
        android.text.ClipboardManager c = (android.text.ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
        CharSequence text = c.getText();
        if (text != null) {
            clipResult = text.toString().trim();
        }
    }
    return clipResult;
}

posted on 2015-07-27 16:13  封起De日子  阅读(378)  评论(0编辑  收藏  举报

导航