0

我正在尝试检查我的应用程序是否忽略了电池优化,我必须强制用户允许该应用程序,我不想被 PlayStore 禁止,我看到一些参考资料说该权限是危险的。然后,直到现在,我正在从下面的代码中尝试这个“解决方案”。我在这里的文档中看到了参考isIgnoringBatteryOptimizations,但是在我的 Android 工作室中它给了我以下错误:

Unresolved reference: isIgnoringBatteryOptimization

我写的代码:

import android.os.PowerManager

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        openPowerSettings(this)    
    }

    private fun openPowerSettings(context: Context) {
        if(PowerManager.isIgnoringBatteryOptimization(context.packageName)){
            val intent = Intent()
            intent.action = Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS
            context.startActivity(intent)
        }
    }
}
4

1 回答 1

2

使用获取PowerManager系统级服务Context#getSystemService(String)

 private fun openPowerSettings(context: Context) {
        val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
        if (powerManager.isIgnoringBatteryOptimizations(context.packageName)) {
            val intent = Intent()
            intent.action = Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS
            context.startActivity(intent)
        }
    }
于 2020-08-19T13:26:41.320 回答