HarmonyOS应用开发-剪贴板功能实现

发布于 2022-3-30 10:37
浏览
0收藏

粘贴版是一个常用的功能,用户通过系统剪贴板服务,可实现应用之间的简单数据传递。例如:在应用A中复制的数据,可以在应用B中粘贴,反之亦可。
效果如图:
HarmonyOS应用开发-剪贴板功能实现-开源基础软件社区
关键代码如下:

public class PasteboardUtils {

    private static final HiLogLabel TAG = new HiLogLabel(HiLog.LOG_APP,0x0,"蛟龙腾飞--粘贴版");

    private SystemPasteboard pasteboard;

    public PasteboardUtils(Context context) {
        initPasteboard(context);
    }
    // 复制到粘贴板
    public void copyText(String text) {
        pasteboard.setPasteData(PasteData.creatPlainTextData(text));
    }

    // 粘贴
    public String pasteText() {
        String result = "";
        PasteData pasteData = pasteboard.getPasteData();
        if (pasteData == null) {
            return result;
        }
        PasteData.DataProperty dataProperty = pasteData.getProperty();
        boolean hasHtml = dataProperty.hasMimeType(PasteData.MIMETYPE_TEXT_HTML);
        boolean hasText = dataProperty.hasMimeType(PasteData.MIMETYPE_TEXT_PLAIN);
        if (hasHtml || hasText) {
            for (int i = 0; i < pasteData.getRecordCount(); i++) {
                PasteData.Record record = pasteData.getRecordAt(i);
                String mimeType = record.getMimeType();
                if (mimeType.equals(PasteData.MIMETYPE_TEXT_HTML)) {
                    result = record.getHtmlText();
                } else if (mimeType.equals(PasteData.MIMETYPE_TEXT_PLAIN)) {
                    result = record.getPlainText().toString();
                } else {
                    HiLog.info(TAG, "%{public}s", "getPasteData mimeType :" + mimeType);
                }
            }
        }
        return result;
    }

    //   监听粘贴版内容
    private final IPasteDataChangedListener listener = new IPasteDataChangedListener() {

        @Override
        public void onChanged() {
            PasteData pasteData = pasteboard.getPasteData();
            if (pasteData != null) {
                HiLog.info(TAG,"粘贴版内容改变:"+pasteData);
            }
        }
    };

    //  清空粘贴板
    public void clearPasteboard(Component component) {
        if (pasteboard != null) {
            pasteboard.clear();
        }
    }

    //初始化
    private void initPasteboard(Context context) {
        pasteboard = SystemPasteboard.getSystemPasteboard(context);
        pasteboard.addPasteDataChangedListener(listener);
    }
}

完整代码地址:
https://gitee.com/jltfcloudcn/jump_to/tree/master/jltf_YKX

标签
HarmonyOS应用开发-剪贴板功能实现.docx 28.29K 6次下载
2
收藏
回复
举报
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源 去关联
    相关推荐