Review and revise the example for Android battery use on 'Writing custom platform-specific code' page
Page URL
https://docs.flutter.dev/development/platform-integration/platform-channels
Page source
No response
Describe the problem
I have had a API23 device(huawei gra ul00) and the battery level code would return 0.
The one that worked for me is the following
val batteryStatus: Intent? = IntentFilter(Intent.ACTION_BATTERY_CHANGED).let { ifilter ->
context.registerReceiver(null, ifilter)
}
val batteryPct: Float? = batteryStatus?.let { intent ->
val level: Int = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
val scale: Int = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
level * 100 / scale.toFloat()
}
if(batteryPct==null)
return -2
return batteryPct.toInt()
Instead of
val batteryManager = getSystemService(Context.BATTERY_SERVICE) as BatteryManager
batteryLevel = batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
Imagined it might help others or give you leads to fix it so others don't have the same problem as I did.
Expected fix
No response
Additional context
No response
Hi @i3130002, is huawei gra ul00 the only device you tested on? Or did the code sample fail on other devices as well?
fwiw, it works just fine on my POCO X3 NFC.
Hi @i3130002, is
huawei gra ul00the only device you tested on? Or did the code sample fail on other devices as well?fwiw, it works just fine on my
POCO X3 NFC.
Unfortunately it was the only one I could have run tests on. But it is worth mentioning that the attached code is from developers.android.com itself https://developer.android.com/training/monitoring-device-state/battery-monitoring
Thanks for the resource. Others may yet run into it, so it'll be nice for them to have the other option in case it doesn't work for them