get Charge Percentage - Android Hardware

Android examples for Hardware:Battery

Description

get 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 float getChargePct(Context context) {
        IntentFilter intentFilter = new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, intentFilter);
        return getChargePct(batteryStatus);
    }// w  w w. j  a  va  2s . c  om

    public static float getChargePct(Intent batteryStatus) {
        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL,
                -1);
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,
                -1);
        return level / (float) scale;
    }
}

Related Tutorials