Android电池电量检测
电池的信息,电压,温度,充电状态等等,都是由BatteryService来提供的。电池的这些信息是BatteryService通过广播 主动把数据传送给所关心的应用程序。
应用如果想要接收到BatteryService发送出来的电池信息,则需要注册一个Intent为Intent.ACTION_BATTERY_CHANGED的BroadcastReceiver。
代码如下: IntentFilter mIntentFilter = new IntentFilter(); mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); registerReceiver(mIntentReceiver, mIntentFilter);
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub String action = intent.getAction(); if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { // 电池状态,返回是一个数字 // BatteryManager.BATTERY_STATUS_CHARGING 表示是充电状态 // BatteryManager.BATTERY_STATUS_DISCHARGING 放电中 // BatteryManager.BATTERY_STATUS_NOT_CHARGING 未充电 // BatteryManager.BATTERY_STATUS_FULL 电池满 int status = intent.getIntExtra("status", 0); // 电池状态 // 电池健康情况,返回也是一个数字 // BatteryManager.BATTERY_HEALTH_GOOD 良好 // BatteryManager.BATTERY_HEALTH_OVERHEAT 过热 // BatteryManager.BATTERY_HEALTH_DEAD 没电 // BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE 过电压 // BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE 未知错误 int health = intent.getIntExtra("health", 0); //电池健康情况 int scale = intent.getIntExtra("scale", 0); // 电池最大容量 int nVoltage = intent.getIntExtra("voltage", 0); // 电池的电压 int level = intent.getIntExtra("level", 0); // 电池的电量,数字 int temperature = intent.getIntExtra("temperature", 0); // 电池的温度 if (nVoltage != 0) { tv_status.setText("电池电量:" + level + "%"); Log.i(TAG, "voltage = " + nVoltage + " level = " + level + " temperature = " + temperature + "...success"); } else { Log.i(TAG, "voltage = " + nVoltage + "...failed"); } } } };