Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to get battery level on Android without permanently monitoring it? [duplicate]

I just need the battery level percentage at one point to print it on the screen, but I don't want to keep monitoring it afterwards.

All code on the internet seems to listen for future changes, but I just need it once. What can be done to get it in a simple way?

like image 340
Sanziana Avatar asked Jun 28 '13 19:06

Sanziana


People also ask

Why is my phone showing two different battery percentages?

The initial mAh capacity value will fall down over time. The device sensors would not be able to pick up on that and that's why you'll get a fixed percentage. So, for example, your battery might be at 90% and then it suddenly, in a matter of minutes, switches to 80%.

What is battery manager in Android?

android.os.BatteryManager. The BatteryManager class contains strings and constants used for values in the Intent. ACTION_BATTERY_CHANGED Intent, and provides a method for querying battery and charging properties.


1 Answers

As stated in Get battery level only once using Android SDK You can use the following code:

public float getBatteryLevel() {
    Intent batteryIntent = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    // Error checking that probably isn't needed but I added just in case.
    if(level == -1 || scale == -1) {
        return 50.0f;
    }

    return ((float)level / (float)scale) * 100.0f; 
}
like image 110
woot Avatar answered Oct 26 '22 22:10

woot