website icon indicating copy to clipboard operation
website copied to clipboard

Review and revise the example for Android battery use on 'Writing custom platform-specific code' page

Open i3130002 opened this issue 4 years ago • 3 comments

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

i3130002 avatar Jan 31 '22 00:01 i3130002

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.

danagbemava-nc avatar Jan 31 '22 11:01 danagbemava-nc

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.

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

i3130002 avatar Jan 31 '22 12:01 i3130002

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

danagbemava-nc avatar Feb 01 '22 09:02 danagbemava-nc