问题
I have a method which periodically runs to keep a network connection alive. During Doze mode, I would like to disable it from running periodically and run exactly once during a maintenance window. When the device comes out of Doze, I would like the method to be called periodically again. How can I accomplish this ?
I have registered a receiver that listens for the PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED
broadcast and then calls PowerManager.isDeviceIdleMode()
. However, this return false for both cases - during a maintenance window and when the device exits Doze mode. How can I differentiate between them ?
回答1:
i faced the same problem, although i think android must differentiate this by sending a different state in the receiver or provide a function to ask such a state, i did not found anything related.
remember, the ACTION_DEVICE_IDLE_MODE_CHANGED is fired again when going back to doze after a period of time of 9-10 minutes.
the solution will be:
CURRENT DEVICE STATUS -> "IN DOZE IDLE"
when you receive ACTION_DEVICE_IDLE_MODE_CHANGED and isDeviceIdleMode() is false your status is "out of doze suspicion" -DO your mantenience window work AND setup an alarm for 15 minutes in the future.
on the next mode change.
if the ACTION_DEVICE_IDLE_MODE_CHANGED is fired before the alarm and isDeviceIdleMode() is true, so, it was a mantenience window. "out of doze false", ( turn off the alarm ).
if the alarm is fired first, this means it was a "out of doze true confirmed" -Do your setup for "out of doze" in the alarm
The timings of doze are in docs. be sure to check that first. ( may change in the future, as already has happened * may be there is a constant to get that value --i don't know ).
i consider this as a hack rather than a full fedged solution. but it works until any future expanded work on android provide another call to ACTION_DEVICE_IDLE_MODE_CHANGED, with "out of doze" status.
来源:https://stackoverflow.com/questions/45649269/how-to-differentiate-between-the-device-entering-a-doze-maintenance-window-and-c