is Battery Low - Android Hardware

Android examples for Hardware:Battery

Description

is Battery Low

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 boolean isBatteryLow(Context context) {
        return getBatteryLevel(context) < 0.15; // 15% matches system low battery level
    }/*from   w  ww .  j  a  va2s . co  m*/

    public static float getBatteryLevel(Context context) {
        Intent batteryStatus = getBatteryStatus(context);
        if (batteryStatus != null) {
            int level = batteryStatus.getIntExtra(
                    BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(
                    BatteryManager.EXTRA_SCALE, -1);
            return (level / (float) scale);
        } else {
            return 0.5f;
        }
    }

    private static Intent getBatteryStatus(Context context) {
        IntentFilter filter = new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED);
        return context.registerReceiver(null, filter);
    }
}

Related Tutorials