Can a third party application get an action once the device goes in to Doze mode?
Trying to register Broadcast receiver for below action,
<receiver android:name="com.doze.sample.DozemodeReceiver" android:enabled="true">
<intent-filter>
<action android:name=" android.os.action.DEVICE_IDLE_MODE_CHANGED" />
</intent-filter>
</receiver>
It's not working (the receiver is not being called).
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.
To confirm what was mentioned in the comments, defining the android.os.action.DEVICE_IDLE_MODE_CHANGED
broadcast receiver via the AndroidManifest.xml has no effect.
The only way to register the receiver is to do it dynamically:
IntentFilter filter = new IntentFilter();
filter.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
context.registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
onDeviceIdleChanged();
}
}, filter);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With