2

I am trying to get the batter level using a BroadCastReceiver:

int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 0);

I have added the following permissions to the AndroidManifest.xml:

<uses-permission android:name="android.permission.BATTERY_STATS" />

When I print the level and scale, I see the default value of 0. Are there additional settings to it?

tshepang
  • 12,111
  • 21
  • 91
  • 136
ssk
  • 9,045
  • 26
  • 96
  • 169
  • Might be worth reading this [blog entry](http://mihaifonoage.blogspot.com/2010/02/getting-battery-level-in-android-using.html) describing how to get at the battery stats.... – t0mm13b Oct 02 '12 at 00:18

2 Answers2

4

Calculating Battery Level in %:

You can find the current battery charge by extracting the current battery level and scale from the battery status intent as shown here:

int level = battery.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = battery.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

float batteryPct = level / (float)scale;

Implement BroadcastReceiver like this:

 BroadcastReceiver mybatteryReceiver= new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                int rawlevel = intent.getIntExtra("level", -1);
                int scale = intent.getIntExtra("scale", -1);
                int level = -1;
                if (rawlevel >= 0 && scale > 0) {
                    level = (rawlevel * 100) / scale;
                }
                Log.d("TEMP","Battery Level in % is:: " + level + "%");
            }
        };

Get a Code from here It is tried and tested. Works fine.

https://www.dropbox.com/s/1y6q5wu526ngz7t/BatteryStats.zip

Result of the code : enter image description here

VendettaDroid
  • 3,131
  • 2
  • 28
  • 41
0

No Permission Required for getting the battery charge status just use the following code in your broadcast receiver :-

int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

This will result in battery Level :)