get Current Battery Charge Percentage - Android Hardware

Android examples for Hardware:Battery

Description

get Current Battery Charge Percentage

Demo Code


//package com.java2s;
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   ww  w .  java 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