register to obtain the battery info; - Android Hardware

Android examples for Hardware:Battery

Description

register to obtain the battery info;

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 {

    private static int sBatteryLevel = 0;

    public static void registerBatteryReceiver(Context context) {

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);

        BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
            @Override/*ww w .j a va  2s. co  m*/
            public void onReceive(Context context, Intent intent) {
                sBatteryLevel = (int) (100f * intent.getIntExtra(
                        BatteryManager.EXTRA_LEVEL, 0) / intent
                        .getIntExtra(BatteryManager.EXTRA_SCALE, 100));
            }
        };
        context.registerReceiver(batteryReceiver, filter);
    }
}

Related Tutorials