You can listen for TYPE_WINDOW_STATE_CHANGED or TYPE_WINDOW_CONTENT_CHANGED events and check which app or activity is currently in the foreground.
Back press usually results in a window change or app closure, so you can infer it by comparing the current and previous window package names or activity classes.
When Home is pressed, your current app/activity will be replaced by the launcher/home screen.
You can follow the below class for detecting Back and Home button actions using AccessibilityService.
I hope it will be helpful for you
class MyAccessibilityService : AccessibilityService() {
private var previousPackageName: String? = null
override fun onAccessibilityEvent(event: AccessibilityEvent) {
if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
val currentPackage = event.packageName?.toString()
// Detect HOME press
if (isLauncherApp(currentPackage)) {
Log.d("AccessService", "Home button pressed")
}
// Detect BACK press (indirectly)
if (previousPackageName != null && currentPackage != previousPackageName) {
Log.d("AccessService", "Possibly back button pressed (window changed)")
}
previousPackageName = currentPackage
}
}
override fun onInterrupt() {}
private fun isLauncherApp(packageName: String?): Boolean {
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_HOME)
val resolveInfo = packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)
return packageName == resolveInfo?.activityInfo?.packageName
}
}