Android 电池电量

2017-04-06  本文已影响297人  王世军Steven

Android 中通过广播获取电池电量信息. 电量信息只能通过动态注册广播才能获取到.

1.0 注册广播的两种方式:

1.4 电量知识点

(1) 电量相关的广播

// 电量发生变化
public static final String ACTION_BATTERY_CHANGED = "android.intent.action.BATTERY_CHANGED";
// 电量低
public static final String ACTION_BATTERY_LOW = "android.intent.action.BATTERY_LOW";
// 从电量低恢复.
// Broadcast Action:  Indicates the battery is now okay after being low.
public static final String ACTION_BATTERY_OKAY = "android.intent.action.BATTERY_OKAY";

(2) BatteryManager

BatteryManager 类中定义了 ACTION_BATTERY_CHANGED广播中Intent所用到的所有的常量和字符串.同时还提供了一个查询电量的方法,和查询充电属性的方法.

下面是两个常用的更多值请参考BatterManager文档

// 电量 
public static final String EXTRA_LEVEL = "level";
// 温度
public static final String EXTRA_TEMPERATURE = "temperature";

1.2 关键代码

释放资源的时候先释放子类,再释放父类.比如在onDestory()中 先解注册,在调用父类的super().onDestory()

/**
 * 注册广播
 */
private void registerBroadcast() {
    // 注册电量广播
    mBatteryReceiver = new BatteryReceiver();
    registerReceiver(mBatteryReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}

/**
 * 电池电量广播接受者
 */
class BatteryReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // 获取电量
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        // 设置图片
        setBatteryImg(level);
    }
}
/**
 * 设置电量图片
 */
private void setBatteryImg(int level) {
    if (level <= 0) {
        ivBattery.setImageResource(R.drawable.ic_battery_0);
    } else if (level <= 10) {
        ivBattery.setImageResource(R.drawable.ic_battery_10);
    } else if (level <= 20) {
        ivBattery.setImageResource(R.drawable.ic_battery_20);
    } else if (level <= 40) {
        ivBattery.setImageResource(R.drawable.ic_battery_40);
    } else if (level <= 60) {
        ivBattery.setImageResource(R.drawable.ic_battery_60);
    } else if (level <= 80) {
        ivBattery.setImageResource(R.drawable.ic_battery_80);
    } else if (level <= 100) {
        ivBattery.setImageResource(R.drawable.ic_battery_100);
    } else {
        ivBattery.setImageResource(R.drawable.ic_battery_100);
    }
}   
/**
 * 释放资源
 */
@Override
protected void onDestroy() {
    // 释放资源 : 先释放子类资源
    if (mBatteryReceiver != null) {
        unregisterReceiver(mBatteryReceiver);
    }
    Log.d(TAG, "-- onDestroy");
    super.onDestroy();
}
上一篇下一篇

猜你喜欢

热点阅读