1.在manifest文件中配置权限:
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
2.在相应的地方加入以下代码
/**
* 忽略电池优化
*/
private void ignoreBatteryOptimization(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
boolean hasIgnored = powerManager.isIgnoringBatteryOptimizations(activity.getPackageName());
// 判断当前APP是否有加入电池优化的白名单,如果没有,弹出加入电池优化的白名单的设置对话框。
if (!hasIgnored) {
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + activity.getPackageName()));
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
} else {
Log.d("ignoreBattery", "hasIgnored");
}
}
}
3.调用代码后就会弹框提示“是否要忽略电池优化?”,用户选择是否。