This is happening me in a Xiaomi device, at least in emulator does not happen.
To be more clear what's happening is the following:
I need that battery optimization disabled to properly run some services from my app.
But without changing configuration what happens is that I get the dialog to warns about battery not being disabled and the need to use it when I start app again, as it had been enabled again.
I don't care much if this is due to personalization layer in the phone and it's usually working on other devices, as I cannot hope to make the app work 100% in any phone terminal, but it would be a problem if battery optimization is enabled again without warning in most devices.
Is there any way to avoid that automatic battery optimization enabling? Or, at the very least, does this usually happen just in a few devices with that API?
Sadly, for some vendors battery optimizations permissions don't actually allow your application to ignore battery optimizations :)
Huawei, Xiaomi, Meizu and some other vendors can block your application from doing it's job even though it has all the permissions. So developers has to think of some workarounds. Also you could reach the Xiaomi tech support to ask them if there is any way to make your application work. Sometimes they can help.
As for requesting the permissions. We use the following code in our application for it and haven't received any complaints yet:
if (isMarshmallowOrHigher()) {
val pm = getSystemService(POWER_SERVICE) as PowerManager
val isIgnoringBatteryOptimizations = pm.isIgnoringBatteryOptimizations(
packageName
)
if (!isIgnoringBatteryOptimizations) {
val intent = Intent()
intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
intent.data = Uri.parse("package:$packageName")
startActivityForResult(intent, ignoreOptimizationsRequest)
}
}