How to Exclude an Android App from Battery Optimization Using Code

How to exclude an Android App from Battery Optimization using code

I think you're having 2 different problems:

1) If you want to keep your app in background you should use a foreground Service. That way your app won't be considered to be in background by the system and the chances of its process being killed are reduced drastically. The downside is that as long as your Service is in foreground you need to show a permanent notification.

2) You cannot exclude your app from battery optimization yourself, but you can prompt the user the settings to whitelist your app. In order to do that you can refer to the official docs, you'll need to add the Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS permission to the manifest and then launch an intent with action ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS. The user will then be able to whitelist your app, only she/he can do that because otherwise every app would whitelist itself and the purpose of the battery optimization would be defied.

Check if battery optimization is enabled or not for an app

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

PowerManager.isIgnoringBatteryOptimizations()

How force the app to opt out of battery saver mode when the service is ON?

The code you use is for battery optimization. Settings-->Batery-->Three Dots Menu Item (...)--->Battery Optimization-->(Choose an app from list)--->Optimize/ Don't optimize.

By choosing Don't optimize you are essentially bypassing Doze, not app standby.

Also be advised that doing this programmatically as you do may result in Google taking your app off the store. It is safer to do it manually following the path i described above.

More on Doze and App Standby here



Related Topics



Leave a reply



Submit