Check if battery optimization is enabled or not for an app

Nik picture Nik · Aug 31, 2016 · Viewed 42.3k times · Source

Android 6 and 7 have some power optimizations (doze mode) which restrict app networking when device is not used.

User may disable optimization mode for any app in Battery settings:

android settings screenshot

Is it possible to check if optimization is enabled for my app or not? I need to ask user to disable optimization for better app functionality, but I don't know how to check it programatically.

Answer

Saurabh Gaddelpalliwar picture Saurabh Gaddelpalliwar · Mar 4, 2019

Add this permission in your manifest.

<uses-permission  android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>

Request White-list / optimization enabled your app

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Intent intent = new Intent();
        String packageName = getPackageName();
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        if (!pm.isIgnoringBatteryOptimizations(packageName)) {
            intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + packageName));
            startActivity(intent);
        }
    }