get Battery Percentage - Android android.os

Android examples for android.os:Battery

Description

get Battery Percentage

Demo Code

import android.app.Application;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

public class Main {

  public static int getBatteryPercentage() {
    try {/*from w  w  w .  j  a  v a2 s .co  m*/
      IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
      Intent batteryStatus = getApplicationUsingReflection().registerReceiver(
          null, ifilter);
      int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
      int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
      int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
      float batteryPct = (level / (float) scale) * 100;
      return (int) batteryPct;
    } catch (Exception e) {
      return 100;
    }
  }

  public static Application getApplicationUsingReflection() throws Exception {
    return (Application) Class.forName("android.app.ActivityThread")
        .getMethod("currentApplication").invoke(null, (Object[]) null);
  }

}

Related Tutorials