return Battery level between 0 and 1. - Android Hardware

Android examples for Hardware:Battery

Description

return Battery level between 0 and 1.

Demo Code


//package com.java2s;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;

public class Main {
    /**/*www.j  av  a  2  s  . co  m*/
     * return between 0 and 1.
     */
    public static float level(final Context context) {
        final IntentFilter ifilter = new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED);
        final Intent batteryStatus = context
                .registerReceiver(null, ifilter);
        final int level = batteryStatus.getIntExtra(
                BatteryManager.EXTRA_LEVEL, -1);
        final int scale = batteryStatus.getIntExtra(
                BatteryManager.EXTRA_SCALE, -1);
        return level / (float) scale;
    }
}

Related Tutorials