Whitelisting an Android application programmatically
suggest changeThe battery-optimization whitelist does not turn Doze off for the device. It lets this app use the network and hold partial wake locks during Doze and App Standby. The intent below needs android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS and is available from API 23.
Whitelisting an Android application programmatically can be done as follows:
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean isIgnoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(getPackageName());
if(!isIgnoringBatteryOptimizations){
Intent intent = new Intent();
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, MY_IGNORE_OPTIMIZATION_REQUEST);
}
The result of starting the activity above can be verified by the following code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_IGNORE_OPTIMIZATION_REQUEST) {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
boolean isIgnoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(getPackageName());
if(isIgnoringBatteryOptimizations){
// Ignoring battery optimization
}else{
// Not ignoring battery optimization
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents