get Battery Percentage - Android Hardware

Android examples for Hardware:Battery

Description

get Battery Percentage

Demo Code


//package com.java2s;
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 va 2  s  . c  o  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) {
            System.out.println(e);
            return 100;
        }
    }

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

Related Tutorials