I am trying to make two toasts: one when the device is charging, and one when it`s not. But the receiver acting crazy, sending many toasts, and crashing the app. I can not f
you can use this code
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, ifilter);
//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();