0

I’m building a React Native Android app where I need to track whenever the user opens another app (e.g., YouTube, Instagram, etc.).

I am using a custom AccessibilityService, but the event for detecting the currently opened app is not being triggered consistently.

  1. What’s happening

    • If I open another app (e.g., Instagram, YouTube, Chrome), no event is logged immediately.

    • But after 1–2 minutes, when I open my own app again, suddenly the service logs the events for those apps retroactively.

    • So events are detected, but only after my app becomes active, not in real-time.

    What I expect

    The AccessibilityService should fire TYPE_WINDOW_STATE_CHANGED or TYPE_WINDOWS_CHANGED events immediately when another app becomes active, even if my app is in the background.

    My current service code

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        if (event == null) return
    
        when (event.eventType) {
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED,
            AccessibilityEvent.TYPE_WINDOWS_CHANGED -> {
                val packageName = event.packageName?.toString()
                Log.d("FocusService", "Detected package: $packageName")
            }
        }
    }
    
    override fun onServiceConnected() {
        super.onServiceConnected()
        serviceInfo = AccessibilityServiceInfo().apply {
            eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED or AccessibilityEvent.TYPE_WINDOWS_CHANGED
            feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC
            notificationTimeout = 0
            flags = AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS or
                    AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
        }
    }
    
    

    What I’ve tried

    • Using TYPE_WINDOW_CONTENT_CHANGED, TYPE_WINDOW_STATE_CHANGED, TYPE_WINDOWS_CHANGED

    • Adding all flags (RETRIEVE_INTERACTIVE_WINDOWS, etc.)

    • Enabling "Accessibility API" from settings

    • Running as foreground service

    • Testing on multiple devices

    Device behavior

    • Works only when my app gains/loses focus

    • Doesn't trigger in real time when user opens other apps

    • Events seem to "queue" and get dispatched later when my app wakes up

    Question

    Why does my AccessibilityService detect other apps only when my app is opened, and not in real time?
    What configuration or permission is required to receive window change events immediately while my app is in the background?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.