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
How to Change the Background Color of a Textfield Without Changing the Border in Javafx
Custom Pagination by Array List
Select the Letters After - in a String
Kafka Consumer in Java Not Consuming Messages
Autowiring Httpservletrequest in Spring Controller
Limiting the Number of Characters in a String, and Chopping Off the Rest
Determine the Number of Pages in a Pdf File
How to Use Limit in Spring Within SQL Query
Kafka: Failed to Update Metadata After 60000 Ms
Avoid Keycloak Default Login Page and Use Project Login Page
Batch Inserts Using JPA Entitymanager
How to Remove All Special Character in a String Except Dot and Comma
How to Write Unit Test for a Setter Method Which Does Not Have a Getter Method
After Spring Boot 2.0 Migration: Jdbcurl Is Required With Driverclassname
How to Run Single Cucumber Feature Files Through Command Prompt and Through Jenkins Using Maven