Android 获取粘贴板的内容

1、获取粘贴板内容,有的手机可能获取到粘贴板的内容,需要监听在onResume()添加getWindow().getDecorView()

 getWindow().getDecorView().post(() -> {
            //获取剪切板内容
             checkNewPassword();
        });

    public static String getClipboardMsg() {
        String clipboardText = "";
        ClipboardManager cm = (ClipboardManager) AppUtil.getApp().getSystemService(CLIPBOARD_SERVICE);
        if (null == cm) {
            return clipboardText;
        }
        ClipData data = cm.getPrimaryClip();
        if (null == data || data.getItemCount() <= 0) {
            return clipboardText;
        }
        ClipData.Item item = data.getItemAt(0);
        if (null == item) {
            return clipboardText;
        }
        CharSequence text = item.getText();
        if (null == text) {
            return clipboardText;
        }
        clipboardText = text.toString();
        return clipboardText;
    }

2、清除粘贴板内容

    /**
     * 清空剪贴板内容
     */
    public static void clearClipboard() {
        ClipboardManager manager = (ClipboardManager) AppUtil.getApp().getSystemService(Context.CLIPBOARD_SERVICE);
        if (manager != null) {
            try {
                manager.setPrimaryClip(manager.getPrimaryClip());
                manager.setText(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

 

你可能感兴趣的:(Android,零碎知识点记录)