2015-03-03 75 views
3

我想使用android創建一個窗口小部件,並且我需要捕獲任何文本選擇事件。例如,用戶正在讀取某物。並在另一個應用程序(網絡瀏覽器,pdf閱讀器,消息)中選擇文本。在另一個應用程序中捕獲文本選擇

是否有可能在後臺捕獲任何文本選擇?

+0

使用剪貼板是最好的方法,下面是一個[示例](http://www.tutorialspoint.com/android/android_clipboard.htm) – Apurva 2015-03-03 06:57:17

+1

@kyur你有沒有發現任何其他應用程序在andorid中檢測到文本選擇我的意思是文本選擇不是文本複製。 – 2016-07-19 12:07:24

+0

我也想要這個。不復制,只有選擇。這可能嗎? – 2017-02-06 16:11:47

回答

1

enter image description here

示例代碼來獲取文本:

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

enter image description here

+0

如何只選擇?不要複製 – 2017-02-06 16:13:04

1

1.you可以定義一個服務在後臺

ClipboardManager clipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
    clipboardManager.setPrimaryClip(new ClipboardManager.OnPrimaryClipChangedListener(){ 
     @Override 
     public void onPrimaryClipChanged() { 
      //TODO do your work 

     } 
    }); 

2.or可以使用AccessibilityService檢測複製文本事件監聽剪貼板事件,監聽「TYPE_VIEW_TEXT_SELECTION_CHANGED」事件並從剪貼板讀取數據,但應指導用戶啓用accessibi在系統的設置中爲您的應用程序切換開關。

相關問題