Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if battery optimization is enabled or not for an app

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.

like image 860
Nik Avatar asked Aug 31 '16 18:08

Nik


People also ask

Should I turn on battery optimization for all apps?

As it turns out, we don't recommend battery optimization apps, as they do more harm than good. See our proven tips for better Android battery life for methods that actually work.


2 Answers

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);         }     } 
like image 181
Saurabh Gaddelpalliwar Avatar answered Oct 16 '22 06:10

Saurabh Gaddelpalliwar


This one was a bit tricky to track down: here's what you are looking for

PowerManager.isIgnoringBatteryOptimizations()

like image 25
FriendlyMikhail Avatar answered Oct 16 '22 06:10

FriendlyMikhail