应用取消电池优化

应用后台运行权限,由电池优化决定
未加入电池优化的白名单时弹出系统选择弹窗,已加入时跳转相应页面

//在manifest文件中配置权限:
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
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 = activity.packageManager.resolveActivity(powerUsageIntent, 0)
            //判断系统是否有这个页面
            if (resolveInfo != null) {
                startActivity(powerUsageIntent)
            }
        }
    }
}

你可能感兴趣的:(android,android)