4

I have an app that needs to ignore doze mode and it asks the user to add it to not optimized apps list the usual way with:

    Intent intent = new Intent();
    String packageName = getPackageName();
    intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
    intent.setData(Uri.parse("package:" + packageName));
    startActivityForResult(intent, BATTERY_OPTIMIZATION_REQUEST);

In onActivityResult() I check if he really added it to "Not optimized" list. So far so so good. My app starts its service which gets and holds a WAKE_LOCK and works permanently (Yes, I know that this drains the battery but my use case requires it).

My problem is that later the user may decide to remove the app from the "Not optimized" list.

My question(s):

  1. Is there a broadcast which I can register for to get notified that battery optimization settings changed?

  2. If not, is there another way to detect that battery optimization setting for my app changed than periodically check its state with isIgnoringBatteryOptimizations()

Initially I thought that in this case the app will be stopped (as when permission is removed) but that is not the case.

Floern
  • 33,559
  • 24
  • 104
  • 119
Ognyan
  • 13,452
  • 5
  • 64
  • 82

1 Answers1

4

There is a system broadcast you can listen to: android.os.action.POWER_SAVE_WHITELIST_CHANGED. It can be found as PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED but that's hidden from the API and undocumented.

Do note that this will be triggered for any change in the battery optimization whitelist, not just your app.

IntentFilter intentFilter = new IntentFilter("android.os.action.POWER_SAVE_WHITELIST_CHANGED");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        // the battery optimization whitelist changed
        // TODO: check if isIgnoringBatteryOptimizations()
    }
};
context.registerReceiver(broadcastReceiver, intentFilter);
Floern
  • 33,559
  • 24
  • 104
  • 119
  • Excellent, I have tested and it is working as expected. It saved my day. This should be an accepted answer. – PSK Aug 28 '20 at 08:23