1、AndroidManifest.xml添加权限
<!-- 取消/关闭电池优化 -->
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
2、MainActivity.class添加判断代码
//关闭电池优化
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!pm.isIgnoringBatteryOptimizations(getPackageName())) {
Toast.makeText(getApplication(), "未关闭电池优化", Toast.LENGTH_SHORT).show();
try{
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivity(intent);
}catch(Exception e){
Toast.makeText(getApplication(), "无法关闭电池优化,请手动关闭!"+e, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplication(), "已关闭电池优化", Toast.LENGTH_SHORT).show();
}
}
网友评论