0

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)
        }
    }
}
alexandre9865
  • 493
  • 2
  • 9
  • 24

1 Answers1

2

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)
        }
    }
Arpan Sarkar
  • 2,301
  • 2
  • 13
  • 24