get Battery Charge - Android Hardware

Android examples for Hardware:Battery

Description

get Battery Charge

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 getBatteryCharge(Context ctx) {
        IntentFilter ifilter = new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = ctx.registerReceiver(null, ifilter);

        int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL,
                -1);/*from  w w  w .ja v a 2s .  c om*/
        int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,
                -1);

        float batteryPct = level / (float) scale;
        return batteryPct;
    }
}

Related Tutorials