未解决的参考:isIgnoringBatteryOptimization

Unresolved reference: isIgnoringBatteryOptimization

我正在尝试检查我的应用程序是否忽略了电池优化,我必须强制用户在其中允许该应用程序,我不想被 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)
        }
    }
}

使用Context#getSystemService(String)

获取PowerManagersystem-level服务
 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)
        }
    }