D'yer Mak'er
D'yer Mak'er

Reputation: 1632

Detect when Power Cable disconnected(USB or AC Charger) in Android programmatically

            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

Upvotes: 1

Views: 3812

Answers (2)

Abhishek Kathait
Abhishek Kathait

Reputation: 61

You can do it simply like this.

Intent intent = getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);

        if (plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB) {
            Toast.makeText(getApplicationContext(), "Device is Charging", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Device not charging", Toast.LENGTH_SHORT).show();
        }

Upvotes: 1

Shlomi Uziel
Shlomi Uziel

Reputation: 908

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

Upvotes: 1

Related Questions