get Battery Status and BroadcastReceiver - Android Hardware

Android examples for Hardware:Battery

Description

get Battery Status and BroadcastReceiver

Demo Code


//package com.java2s;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import android.os.BatteryManager;

public class Main {
    public static float getBatteryStatus(Context context) {
        try {/*from   ww w  .j a  va2s  .c o m*/
            IntentFilter ifilter = new IntentFilter(
                    Intent.ACTION_BATTERY_CHANGED);
            BroadcastReceiver receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                }
            };
            Intent batteryStatus = context.getApplicationContext()
                    .registerReceiver(receiver, ifilter);
            int level = batteryStatus.getIntExtra(
                    BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(
                    BatteryManager.EXTRA_SCALE, -1);
            return ((float) level / (float) scale) * 100.0f;
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Error e) {
            e.printStackTrace();
        }
        return 20;
    }
}

Related Tutorials