Android unable read window content on few devices using accessibility service

前端 未结 3 814
一整个雨季
一整个雨季 2020-12-18 02:48

My requirement: Reading the text from pop up, dialog etc for particular app.

I have implemented an accessibility service and I am receiving proper events and data as

3条回答
  •  借酒劲吻你
    2020-12-18 03:15

    This is the code I use and it works for me:

    public class USSDService extends AccessibilityService {
    
    public static String TAG = USSDService.class.getSimpleName();
    
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        Log.d(TAG, "onAccessibilityEvent");
    
        AccessibilityNodeInfo source = event.getSource();
        if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && !String.valueOf(event.getClassName()).contains("AlertDialog")) {
            return;
        }
        if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && (source == null || !source.getClassName().equals("android.widget.TextView"))) {
            return;
        }
        if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED && TextUtils.isEmpty(source.getText())) {
            return;
        }
    
        List eventText;
    
        if(event.getEventType() == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            eventText = event.getText();
        } else {
            eventText = Collections.singletonList(source.getText());
        }
    
        String text = processUSSDText(eventText);
    
        if( TextUtils.isEmpty(text) ) return;
    
        // Close dialog
        performGlobalAction(GLOBAL_ACTION_BACK); // This works on 4.1+ only
    
        Log.d(TAG, text);
        // Handle USSD response here
    
    }
    
    private String processUSSDText(List eventText) {
        for (CharSequence s : eventText) {
            String text = String.valueOf(s);
            // Return text if text is the expected ussd response
            if( true ) {
                return text;
            }
        }
        return null;
    }
    
    @Override
    public void onInterrupt() {
    }
    
    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.d(TAG, "onServiceConnected");
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.flags = AccessibilityServiceInfo.DEFAULT;
        info.packageNames = new String[]{"com.android.phone"};
        info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
        setServiceInfo(info);
    }
    }
    

    Declare it in Android manifest

    
    
        
    
    
    

    Create a xml file that describes the accessibility service called ussd_service

    
    
    

提交回复
热议问题