Skip to content

Commit 59f079c

Browse files
Update ScreenOperatorAccessibilityService.kt
1 parent 3e4a095 commit 59f079c

1 file changed

Lines changed: 47 additions & 7 deletions

File tree

app/src/main/kotlin/com/google/ai/sample/ScreenOperatorAccessibilityService.kt

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -978,20 +978,60 @@ class ScreenOperatorAccessibilityService : AccessibilityService() {
978978
fun pressEnterKey() {
979979
Log.d(TAG, "Pressing Enter key")
980980
try {
981-
val result = performGlobalAction(AccessibilityService.GLOBAL_ACTION_ENTER)
982-
if (result) {
983-
Log.d(TAG, "Successfully pressed Enter key")
984-
showToast("Enter-Taste erfolgreich gedrückt", false)
985-
} else {
986-
Log.e(TAG, "Failed to press Enter key")
987-
showToast("Fehler beim Drücken der Enter-Taste", true)
981+
// Für Android 11+ (API 30+) können wir GLOBAL_ACTION_ENTER verwenden
982+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
983+
val result = performGlobalAction(AccessibilityService.GLOBAL_ACTION_ENTER)
984+
if (result) {
985+
Log.d(TAG, "Successfully pressed Enter key using GLOBAL_ACTION_ENTER")
986+
showToast("Enter-Taste erfolgreich gedrückt", false)
987+
return
988+
}
988989
}
990+
991+
// Fallback für ältere Android-Versionen: Suche nach fokussiertem Element und führe Aktion aus
992+
val rootNode = rootInActiveWindow
993+
if (rootNode != null) {
994+
val focusedNode = findFocusedNode(rootNode)
995+
if (focusedNode != null) {
996+
val result = focusedNode.performAction(AccessibilityNodeInfo.ACTION_CLICK)
997+
focusedNode.recycle()
998+
if (result) {
999+
Log.d(TAG, "Successfully pressed Enter key using ACTION_CLICK on focused node")
1000+
showToast("Enter-Taste erfolgreich gedrückt", false)
1001+
return
1002+
}
1003+
}
1004+
rootNode.recycle()
1005+
}
1006+
1007+
Log.e(TAG, "Failed to press Enter key")
1008+
showToast("Fehler beim Drücken der Enter-Taste", true)
9891009
} catch (e: Exception) {
9901010
Log.e(TAG, "Error pressing Enter key: ${e.message}")
9911011
showToast("Fehler beim Drücken der Enter-Taste: ${e.message}", true)
9921012
}
9931013
}
9941014

1015+
/**
1016+
* Find the focused node in the accessibility tree
1017+
*/
1018+
private fun findFocusedNode(node: AccessibilityNodeInfo): AccessibilityNodeInfo? {
1019+
if (node.isFocused) {
1020+
return AccessibilityNodeInfo.obtain(node)
1021+
}
1022+
1023+
for (i in 0 until node.childCount) {
1024+
val child = node.getChild(i) ?: continue
1025+
val focusedNode = findFocusedNode(child)
1026+
child.recycle()
1027+
1028+
if (focusedNode != null) {
1029+
return focusedNode
1030+
}
1031+
}
1032+
1033+
return null
1034+
}
9951035

9961036
/**
9971037
* Open an app by package name

0 commit comments

Comments
 (0)