Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android M listening to android.os.action.DEVICE_IDLE_MODE_CHANGED

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).

like image 773
Rupali Avatar asked Jul 22 '15 09:07

Rupali


2 Answers

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.

like image 108
vanomart Avatar answered Nov 15 '22 15:11

vanomart


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);
like image 42
zmarties Avatar answered Nov 15 '22 16:11

zmarties