BroadcastReceiver mBatteryReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
String batteryPercentage = String.valueOf(level);
Log.d("battery",batteryPercentage);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
Log.d("ischarging", String.valueOf(isCharging));
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
String action = intent.getAction();
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
if (plugged == BatteryManager.BATTERY_PLUGGED_AC && DefaultManager.acChargeConnect && level >= DefaultManager.batteryPercentageTriggerValue) {
//do something
} else if (plugged == BatteryManager.BATTERY_PLUGGED_USB && DefaultManager.usbConnect){
//do something
} else if (plugged == 0) {
// on battery power
} else {
// intent didnt include extra info
}
}
};
So I want to detect when the power cable or usb cord is disconnected and do something when that event happens.
I have gone through BatteryManager
documentation and have tried a few constants mentioned there but nothing seems to be working. I would like to capture the charger disconnected event to do something. Any pointer is appreciated. thanks
See answer here for the proper actions to listen to: How to detect power connected state?
Also, don't create anonymous BroadcastReceiver, since it has to be registered in your AndroidManifest.xml