How can I programatically monitor the battery level on my android device ? I have read the examples posted on stackoverflow and the BatteryManager
documentation where we need to register the Receiver for ACTION_BATTERY_CHANGED
. My question is that I need to continuosly monitor the Battery level . When I use ACTION_BATTERY_CHANGED
intent the update stays at a constant value till I exit and re-launch my app. Is there a way to monitor the battery level for the entire duration that my app is running?
Just try to use following code, if you run it, you get different information for of the battery. There are also a lot more infos you can get, but therefore you should just pic the right commands in the android api for the battery.
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();
}