It has the same function as Taobao Taobao Password. Open the app to monitor the pasteboard function. The function that used to be good suddenly didn't work.
After investigation is
clipManager.hasPrimaryClip() return false
After spending "nine bulls and two tigers" (google it)
In Android 10, only the default input method (IME) or the currently focused application can access the clipboard data.
It was originally monitored in onStart. So we changed to onResume to monitor. And add a delay of 200ms. This is ok.
The tool class of the pasteboard is attached below
public class ClipboardUtils {
//获取粘贴板的信息
public static void getContent(Context context) {
try {
ClipboardManager clipManager = (ClipboardManager) context.getSystemService(CLIPBOARD_SERVICE);
//无数据时直接返回
if (clipManager == null || !clipManager.hasPrimaryClip()) {
return;
}
//如果是文本信息
if (clipManager != null && clipManager.getPrimaryClipDescription() != null && clipManager.getPrimaryClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
ClipData clip = clipManager.getPrimaryClip();
if (clip != null) {
ClipData.Item item = clip.getItemAt(0);
if (item.getText() != null) {
//此处是TEXT文本信息
String content = item.getText().toString();
//todo
//做你自己的逻辑处理.处理完成记得清空粘贴板.
//clipManager.setText("");
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void copyString(Context context, String content) {
ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
if (StringUtil.isNotNull(content)) {
cm.setText(content);
ToastUtils.toastShort("");
} else {
ToastUtils.toastShort("");
}
}
}