如何以编程方式监控Android设备上的电池电量?我已经阅读了stackoverflow上发布的示例和我需要注册Receiver for BatteryManager
的{{1}}文档。我的问题是我需要持续监控电池电量。当我使用ACTION_BATTERY_CHANGED
意图时,更新将保持恒定值,直到我退出并重新启动我的应用程序。有没有办法在我的应用运行的整个持续时间内监控电池电量?
答案 0 :(得分:3)
尝试使用以下代码,如果您运行它,您将获得有关电池的不同信息。你还可以获得更多的信息,但是你应该在android api中为电池拍摄正确的命令。
public void getActualData(){
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, ifilter);
//are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging == true){
tvCharged.setText("CHARGING");
}else{
tvCharged.setText("NOT CHARGING");
}
//how are we charging
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
if(usbCharge == true){
tvHowCharging.setText("USB");
}else{
tvHowCharging.setText("ELECTRICAL OUTLET");
}
//get battery level and print it out
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
tvLevelOutput.setText(level + " / 100");
pbLevel.setProgress(level);
pbLevel.invalidate();
//get battery temperatur
int temp = batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
tvTempOutput.setText(temp + "Grad");
pbTemp.incrementProgressBy(temp);
pbTemp.invalidate();
//get battery voltage
int voltage = batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
tvVoltageOutput.setText(voltage + " V");
pbVoltage.incrementProgressBy(voltage);
pbVoltage.invalidate();
}