Sample Code :
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (pm != null && !pm.isIgnoringBatteryOptimizations(getPackageName())) {
askIgnoreOptimization();
} else {
// already ignoring battery optimization code here next you want to do
}
} else {
// already ignoring battery optimization code here next you want to do
}
Declare static variable
private static final int IGNORE_BATTERY_OPTIMIZATION_REQUEST = 1002;
show dialog for BATTERY_OPTIMIZATIONS
private void askIgnoreOptimization() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, IGNORE_BATTERY_OPTIMIZATION_REQUEST);
} else {
openNextActivity();
}
}
also need to add permission to manifest file i.e as below
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
Maybe this code is helpful to you!