Android M listening to android.os.action.DEVICE_IDLE_MODE_CHANGED

前端 未结 2 369
既然无缘
既然无缘 2021-02-04 15:57

Can a third party application get an action once the device goes in to Doze mode?

Trying to register Broadcast receiver for below action,



        
相关标签:
2条回答
  • 2021-02-04 16:56

    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);
    
    0 讨论(0)
  • 2021-02-04 16:57

    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.

    0 讨论(0)
提交回复
热议问题