Android Development: Show Battery Level
Solution 1
if you mean changing the battery status on the emulator do the following. Connect to the emulator via telnet and change the status and capacity
> telnet localhost 5554
Android Console: type 'help' for a list of commands
OK
power ac off
OK
power discharging
OK
power capacity 21
OK
exit
>
Ahh, well you can do what it says on the page Ted mentioned, and then use a handler to show a toast. This is the code you need to add to your activity.
private Handler handler = new Handler;
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Log.i(TAG, "level: " + level + "; scale: " + scale);
int percent = (level*100)/scale;
final String text = String.valueOf(percent) + "%";
handler.post( new Runnable() {
public void run() {
Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
}
});
}
};
Solution 2
To get the battery level right now, call:
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
(note: typing that in from memory, please adjust if needed)
This will return an Intent
with various extras documented on the BatteryManager
class. Use BatteryManager.EXTRA_LEVEL
and BatteryManager.EXTRA_SCALE
to determine the percentage remaining.
If you need to know over a period of time as the battery changes, use the BroadcastReceiver
approach @Augusto outlined in his answer.
Solution 3
public static String batteryLevel(Context context)
{
Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
int percent = (level*100)/scale;
return String.valueOf(percent) + "%";
}
carefacerz
Updated on July 03, 2022Comments
-
carefacerz almost 2 years
I've been searching for this and only find really messed up things. Isn't there a easy way to show the battery level like 21% on a toast or Textview? Or how can i achieve this?
//Simon
-
carefacerz almost 13 yearsSorry, i mean like BatteyManager.getLevel() but there isnt. so basicly just show how much battery procentage i have on my phone
-
CommonsWare almost 13 years@Augusto: Ideally, use
BatteryManager.EXTRA_LEVEL
instead of"level"
. Also, the level is not a percentage. It is a value ranging from 0 to the value of theBatteryManager.EXTRA_SCALE
extra. On many devices, the scale is 100, but do not assume that. -
Victor about 10 yearsDon't forget to register the receiver: this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); :)