get Current Battery Charge Percentage - Android android.os

Android examples for android.os:Battery

Description

get Current Battery Charge Percentage

Demo Code

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

public class Main {

  public static int getCurrentBatteryChargePercentage(Context context) {
    IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = context.registerReceiver(null, iFilter);

    final int DefaultValue = 0;

    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL,
        DefaultValue);/*from  www .j  a  v a  2s .c o  m*/
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,
        DefaultValue);

    int batteryPct = calculateBatteryPercentage(level, scale);

    return batteryPct;
  }

  private static int calculateBatteryPercentage(int level, int scale) {
    return Math.round((level / (float) scale) * 100);
  }

}

Related Tutorials