为了保持Service后台服务运行,关闭电池优化,在休眠和最小化时能持续执行。
关于Service保活,后面会再说一篇
这里我们简单的说,就是两步
两个部分
AndroidManifest.xml 加权限
//在manifest文件中配置权限:
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
java代码,
//电池优化
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){
Intent intentpm = new Intent();
String packageName = getApplicationContext().getPackageName();
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(mcontext.POWER_SERVICE);
//这个方法返回true的时候表明已经关闭,false则是已开启优化
if (pm.isIgnoringBatteryOptimizations(packageName))
intentpm.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
else
{
intentpm.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intentpm.setData(Uri.parse("package:" + packageName));
}
mcontext.startActivity(intentpm);
}
kotlin代码,
import android.os.PowerManager
import android.provider.Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS
import android.provider.Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
/**
* 忽略电池优化
*/
private fun ignoreBatteryOptimization(activity: Activity) {
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
var hasIgnored = false
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
hasIgnored = powerManager.isIgnoringBatteryOptimizations(activity.packageName)
// 判断当前APP是否有加入电池优化的白名单,如果没有,弹出加入电池优化的白名单的设置对话框。
if (!hasIgnored) {
//未加入电池优化的白名单 则弹出系统弹窗供用户选择(这个弹窗也是一个页面)
val intent = Intent(ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
intent.data = Uri.parse("package:" + activity.packageName)
startActivity(intent)
}else{
//已加入电池优化的白名单 则进入系统电池优化页面
val powerUsageIntent = Intent(ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS)
val resolveInfo = packageManager.resolveActivity(powerUsageIntent, 0)
//判断系统是否有这个页面
if (resolveInfo != null) {
startActivity(powerUsageIntent)
}
}
}
}
参考自: