I want to find the URL of the current tab using accessibility service. When I open the tab I can't get the URL, but I can get the texts displayed on the screen.
I am using the following code:`
public class ASUrl extends AccessibilityService {
private static final String TAG = ASUrl.class
.getSimpleName();
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
AccessibilityNodeInfo source = event.getSource();
if (source == null)
return;
final String packageName = String.valueOf(source.getPackageName());
// Add browser package list here (comma seperated values)
String BROWSER_LIST = "";
List<String> browserList
= Arrays.asList(BROWSER_LIST.split(",\\s*"));
if (event.getEventType()
== AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED) {
if (!browserList.contains(packageName)) {
return;
}
}
if (browserList.contains(packageName)) {
try {
// App opened is a browser.
// Parse urls in browser.
if (AccessibilityEvent
.eventTypeToString(event.getEventType())
.contains("WINDOW")) {
AccessibilityNodeInfo nodeInfo = event.getSource();
getUrlsFromViews(nodeInfo);
}
} catch(StackOverflowError ex){
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Method to loop through all the views and try to find a URL.
* @param info
*/
public void getUrlsFromViews(AccessibilityNodeInfo info) {
try {
if (info == null)
return;
if (info.getText() != null && info.getText().length() > 0) {
String capturedText = info.getText().toString();
if (capturedText.contains("https://")
|| capturedText.contains("http://")) {
Log.i(TAG, "Captured "+ capturedText);
}
}
for (int i = 0; i < info.getChildCount(); i++) {
AccessibilityNodeInfo child = info.getChild(i);
getUrlsFromViews(child);
if(child != null){
child.recycle();
}
}
} catch(StackOverflowError ex){
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public void onInterrupt() {
}
}`
I can't get the url. My XML is below:
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityFeedbackType="feedbackGeneric"
android:accessibilityFlags="flagDefault|flagIncludeNotImportantViews|flagRequestTouchExplorationMode|flagRequestEnhancedWebAccessibility|flagReportViewIds|flagRetrieveInteractiveWindows"
android:canPerformGestures="true"
android:canRetrieveWindowContent="true"
android:accessibilityEventTypes="typeWindowStateChanged|typeWindowContentChanged|typeAllMask"
/>
I have looked at other solutions like Android : Read Google chrome URL using accessibility service, but this didn't help.
The code gives the URL the first time, but it doesn't work after that.
I am testing on Android 8.1.0, API27.