我想使用android创建一个小部件,我需要捕获任何文本选择事件。例如,用户正在读取某事。并在另一个应用程序(网页浏览器,PDF阅读器,消息传递)中选择文本。
可以在后台捕捉任何文字选择吗?
答案 0 :(得分:1)
尝试此操作从剪贴板中获取文本
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.getText();
答案 1 :(得分:1)
示例代码:
String textToPaste = null;
ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
/* Returns true if there is currently a primary clip on the clipboard. */
if (clipboard.hasPrimaryClip()) {
ClipData clip = clipboard.getPrimaryClip();
// if you need text data only, then you have to check the MIME type for Text as i shown below :
if (clip.getDescription().hasMimeType(MIMETYPE_TEXT_PLAIN))
// WARNING: The item could cantain URI that points to the text data.
// In this case the getText() returns null and this code fails!
textToPaste = clip.getItemAt(0).getText().toString();
// or you may coerce the data to the text representation: i have explained this in the second image.
textToPaste = clip.getItemAt(0).coerceToText(this).toString();
}
if (!TextUtils.isEmpty(textToPaste))
((TextView)findViewById(R.id.etInput1)).setText(textToPaste);
欲了解更多信息,请查看官方链接
http://developer.android.com/reference/android/content/ClipData.html
http://developer.android.com/reference/android/content/ClipboardManager.html
答案 2 :(得分:1)
1.您可以定义服务以在后台监听剪贴板事件
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboardManager.setPrimaryClip(new ClipboardManager.OnPrimaryClipChangedListener(){
@Override
public void onPrimaryClipChanged() {
//TODO do your work
}
});
2.或者您可以使用AccessibilityService来检测复制文本事件,监听" TYPE_VIEW_TEXT_SELECTION_CHANGED"事件和从剪贴板读取数据,但您应引导用户在系统设置中为您的应用启用辅助功能切换。