How to check if my app has been configured battery optimized on Android?

1.9k views Asked by At

I'm wondering if there's any way in React Native that allows us to know if user has been selected "Battery Optimized" for our app?

1

There are 1 answers

1
Karan Harsh Wardhan On BEST ANSWER

in native android,You can use PowerManager.isIgnoringBatteryOptimizations() boolean to determine if an application is already ignoring optimizations ie whether the app is on the whitelist .

 @ReactMethod public void isAppIgnoringBatteryOptimization(Callback callback){
    String packageName = getReactApplicationContext().getPackageName();
    PowerManager pm = (PowerManager) getReactApplicationContext().getSystemService(Context.POWER_SERVICE);
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      callback.invoke(pm.isIgnoringBatteryOptimizations(packageName));
    }else{
      callback.invoke(true);
    }

and then in js

 isAppIgnoringBatteryOptimization: function(callback) {
    jobModule.isAppIgnoringBatteryOptimization(ignoringOptimization => {
      if (ignoringOptimization != null) {
        callback("", ignoringOptimization);
      } else {
        callback("error", null);
      }
    });
  }

https://github.com/vikeri/react-native-background-job/ is a good library that sees all the edge cases of background execution

If you want to ask user to turn it off - ask for

Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission

from

https://developer.android.com/reference/android/provider/Settings#ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS