javaandroidphone-state-listenerandroid-doze

How to create PhoneStateListener that works in both Doze Mode and Power Saving Mode?


When device enters Doze mode or Power Saving mode my PhoneStateListener stops to work. Also I need to register PhoneStateListener on device reboot. I don't want to use BroadcastReceiver because it is not recommended anymore, see https://developer.android.com/about/versions/oreo/background#broadcasts


Solution

  • I don't think BroadcastReceiver are not recommended is the right definition at this point , its just has more limitations such as register broadcast receivers for implicit broadcasts in the manifest and according to docs :

    • Apps can continue to register for explicit broadcasts in their manifests
    • Apps can use Context.registerReceiver() at runtime to register a receiver for any broadcast, whether implicit or explicit.

    Doze mode has few restrictions but it provide a solution for firing alarms at Doze mode an Power Saving Mode using AlarmManager :

    If you need to set alarms that fire while in Doze, use setAndAllowWhileIdle() or setExactAndAllowWhileIdle().

    You should about setAndAllowWhileIdle and setExactAndAllowWhileIdle and decide which one is relevant for you .