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?
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 :
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 :)