我想使用可访问性服务找到当前选项卡的URL。当我打开选项卡时,无法获取URL,但是可以获取屏幕上显示的文本。
我正在使用以下代码:`
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() {
}
}`
我找不到网址。我的XML如下:
<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"
/>
我查看了其他解决方案,例如Android : Read Google chrome URL using accessibility service,但这无济于事。
该代码是第一次提供该URL,但此后将不起作用。
我正在Android 8.1.0,API27上进行测试。