get Current Battery Level - Android Hardware

Android examples for Hardware:Battery

Description

get Current Battery Level

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 final float BATTERY_LEVEL_UNKNOWN = -1;

    public static float getCurrentBatteryLevel(Context context) {
        IntentFilter ifilter = new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);
        if (batteryStatus != null) {
            int level = batteryStatus.getIntExtra(
                    BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(
                    BatteryManager.EXTRA_SCALE, -1);
            return level / (float) scale;
        }// w w w . ja  v a2s  .c  o m
        return BATTERY_LEVEL_UNKNOWN;
    }
}

Related Tutorials