androidkotlinandroid-powermanager

Unresolved reference: isIgnoringBatteryOptimization


I'm trying to check if my application is ignoring the battery optimization, I have to force users allow the application in that, I don't wanna to be banned from PlayStore, I saw some references saying that the permission is dangerous. Then, until now, I'm trying this "solution" from code below. I saw the reference in documentation here isIgnoringBatteryOptimizations, but in my Android studio it gives me the follow error:

Unresolved reference: isIgnoringBatteryOptimization

The code I wrote:

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)
        }
    }
}

Solution

  • Get PowerManager system-level service using 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)
            }
        }