簡體   English   中英

AccessibilityService獲取選定的文本

[英]AccessibilityService get selected text

我正在創建AccesibilityService,該服務需要在其他應用程序中獲取選定的文本。

我用於服務的xml資源如下所示:

<?xml version="1.0" encoding="utf-8"?>
<accessibility-service
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:accessibilityEventTypes="typeViewTextSelectionChanged"
    android:accessibilityFeedbackType="feedbackSpoken"
    android:canRetrieveWindowContent="true"
    android:notificationTimeout="100"
    android:settingsActivity="com.example.android.apis.accessibility.TestBackActivity"/>

和Java代碼

@Override
public void onServiceConnected(){

    AccessibilityServiceInfo info = new AccessibilityServiceInfo();
    info.eventTypes = AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED;
    info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
    info.notificationTimeout = 100;
    this.setServiceInfo(info);
    Toast.makeText(this,"Connected",Toast.LENGTH_LONG).show();
}

@Override
public void onAccessibilityEvent(AccessibilityEvent event)
{
    Toast.makeText(this,"Got event",Toast.LENGTH_LONG).show();

    final int selectBegin = event.getSource().getTextSelectionStart();
    final int selectEnd = event.getSource().getTextSelectionEnd();
    if (selectBegin == selectEnd)
    {
        return;
    }
    String text = event.getText().toString().substring(selectBegin,selectEnd + 1);
the rest of code...
}

@Override
public void onInterrupt()
{
    return;
}

@Override
public void onDestroy()
{
    super.onDestroy();
    Toast.makeText(this,"Stopped",Toast.LENGTH_LONG).show();
}

發生選擇后,這應該從任何其他應用程序獲取文本。

它僅在我的應用程序中有效,我使用其中包含隨機文本的TextView進行了活動,選擇它之后,事件被正確拋出。 但是進入任何其他應用程序(例如chrome),一些隨機的pdf閱讀器應用程序后,都不會引發任何事件,至少不是我正在監聽的該事件。

@Edit從xml中刪除了此行。 現在引發事件,但是選擇的索引為-1和-1

android:packageNames="com.example.jakubjab.getselectedtext"

至少您的XML配置已關閉:

android:packageNames="com.example.jakubjab.getselectedtext"

您需要省略此行。 packageNames參數限制從中獲取事件的軟件包。 不設置將導致從每個程序包中獲取事件。

鑒於您對問題的解釋,我想這將解決您的問題。 至少,這是一個問題,如果不能正確解決,則可能需要提供更多詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM