max
max

Reputation: 41

Android ACTION_DEVICE_IDLE_MODE_CHANGED not fired

Device: Samsung Tab A 2018 10.5 Software: Android 9

I have a broadcast receiver that is registered for the intent ACTION_DEVICE_IDLE_MODE_CHANGED. That's because I would like to stop a networking coroutine job once the app has fallen into deep sleep (IDLE) mode.

The problem is that my broadcast receiver never receives this intent, even though it is registered (I checked it!). Even more confusing is the fact that, once I put the device into IDLE mode via command line with adb shell dumpsys battery unplug and then adb shell dumpsys deviceidle step, the intent is actually triggered and my broadcast receiver receives the intent.

However, in regular usage mode (that is, not connected to power) I know that my app goes into IDLE mode after roughly 5 minutes because I can see on my server that the client connection to my app has timed out.

So after all, why my broadcast receiver is not notified when the device falls into IDLE mode?

My BroadcastReceiver:

class IdleStateListener(context: Context?, private val networkingImpl: Networking): CustomBroadcastReceiver() {

    private val pm = context?.getSystemService(Context.POWER_SERVICE) as PowerManager
    override var isRegistered = false

    override fun onReceive(context: Context?, intent: Intent?) {
        val action = intent?.action
        if (action == PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED){
            if (pm.isDeviceIdleMode){
                println("IDLE")
                networkingImpl.onDeviceFellAsleep()
            }
        }
    }
} 

Registering the receiver:

private var idleStateListener = IdleStateListener(context, this)
if (!idleStateListener.isRegistered) {
            println("Registering idle state listener")
            context.registerReceiver(idleStateListener, IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED))
            idleStateListener.isRegistered = true
        }

My abstract CustomBroadcastReceiver class:

abstract class CustomBroadcastReceiver: BroadcastReceiver() {
    abstract var isRegistered: Boolean
}

Thanks in advance!

Upvotes: 3

Views: 1091

Answers (0)

Related Questions