Android 10以后需要获取焦点才能读到剪切板数据
@Override
public void onWindowFocusChanged(boolean hasFocus) {
}
数据获取
public String getClipboardContent(Context context) {
ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (cm != null) {
ClipData data = cm.getPrimaryClip();
if (data != null && data.getItemCount() > 0) {
ClipData.Item item = data.getItemAt(0);
if (item != null) {
CharSequence sequence = item.coerceToText(context);
if (sequence != null) {
return sequence.toString();
}
}
}
}
return "";
}
清空剪切板
public void clearClipboard() {
ClipboardManager cm = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
if (cm != null) {
cm.setPrimaryClip(ClipData.newPlainText(null, null));
}
}
网友评论