权限
<!--系统保活-->
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
在onCreate
//保活
boolean ignoringBatteryOptimizations = isIgnoringBatteryOptimizations();
if (ignoringBatteryOptimizations){
Toast.makeText(this, "本应用在白名单", Toast.LENGTH_SHORT).show();
}else {
requestIgnoreBatteryOptimizations();
}
方法
/**
* 判断是否在白名单中
* @return
*/
@RequiresApi(api = Build.VERSION_CODES.M)
private boolean isIgnoringBatteryOptimizations() {
boolean isIgnoring = false;
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
if(powerManager != null) {
isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
}
return isIgnoring;
}
/**
* 申请成为白名单
*/
@RequiresApi(api = Build.VERSION_CODES.M)
public void requestIgnoreBatteryOptimizations() {
try{
Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:"+ getPackageName()));
startActivity(intent);
} catch(Exception e) {
e.printStackTrace();
}
}
请求结果
/**
* 保活
*/
boolean ignoringBatteryOptimizations = isIgnoringBatteryOptimizations();
if (ignoringBatteryOptimizations){
Toast.makeText(this, "OK", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "failure", Toast.LENGTH_SHORT).show();
}