Android development: display battery level

I searched for it and only find really spoiled things. Isn’t there a simple way to show the battery level, for example, 21% on a toast or Textview? Or how can I achieve this?

//Simon

+4
source share
4 answers

If you mean a change in battery status on the emulator, follow these steps: Connect to the emulator via telnet and change the state 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 > 

Well, you can do what he says on the page mentioned by Ted, and then use a handler to show the 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(); } }); } }; 
+10
source

To get the battery level right now, call:

 registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 

(note: typing this from memory, adjust if necessary)

This will return the Intent with the various add-ons described in the BatteryManager class. Use BatteryManager.EXTRA_LEVEL and BatteryManager.EXTRA_SCALE to determine the remaining percentage.

If you need to know for a certain period of time when changing the battery, use the BroadcastReceiver @Augusto approach specified in his answer.

+14
source
  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) + "%"; } 
+5
source

You can use this.

 private void batteryLevel() { BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { //context.unregisterReceiver(this); int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1); int level = -1; if (rawlevel >= 0 && scale > 0) { level = (rawlevel * 100) / scale; } batterLevel.setText("Battery Level Remaining: " + level + "%"); } }; IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(batteryLevelReceiver, batteryLevelFilter); } 
0
source

All Articles