Building on a perfect answer provided by @zmarties, here is the full solution:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
BroadcastReceiver receiver = new BroadcastReceiver() {
@RequiresApi(api = Build.VERSION_CODES.M) @Override public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm.isDeviceIdleMode()) {
// the device is now in doze mode
} else {
// the device just woke up from doze mode
}
}
};
context.registerReceiver(receiver, new IntentFilter(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED));
}
In case you are able to check when the context is destroyed (e.g. in the activity or service), call this to avoid leaking resources:
context.unregisterReceiver(receiver);
To test this piece of code, use the following commands:
adb shell dumpsys deviceidle force-idle
to bring the device into doze mode,
adb shell dumpsys deviceidle step
To wake up the device from Doze.