简体   繁体   中英

AccessibilityService get selected text

I am creating AccesibilityService which needs to get selected text in other apps.

My xml resource for service looks like this:

<?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"/>

and java code

@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();
}

This should get text from any other app after selection occures.

It works only in my app, I made activity with TextView with random text in it and after I select it, event is thrown correctly. But after entering any other app, for example chrome, some random pdf reader app, no event is thrown, at least not this one I'm listening on.

@Edit Removed this line from xml. Now event is thrown, but indices of selection are -1 and -1

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

At the very least your XML configuration is off:

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

You need to omit this line. The packageNames parameter limits the packages from which you get events. Not setting in results in getting events from every package.

Given your explanation of the problem, I imagine this will fix your issue. At the very least, this is a problem, and if it doesn't fix it out right, you may need to provide more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM