Isaac
Isaac

Reputation: 12874

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

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?

Upvotes: 4

Views: 2139

Answers (1)

Karan Harsh Wardhan
Karan Harsh Wardhan

Reputation: 1126

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

Upvotes: 4

Related Questions