Tuesday, February 25, 2014

How to detect whether phone is in charging

Does not need register a broadcast receiver. Call function
registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)), and it will return anIntent with battery status immediately, because Intent.ACTION_BATTERY_CHANGED is a sticky broadcast.
Here is code snap:
        Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean cableCharge = plugged == BatteryManager.BATTERY_PLUGGED_USB
                || plugged == BatteryManager.BATTERY_PLUGGED_AC;
        boolean wirelessCharge = plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;

No comments:

Post a Comment

Enable HP Zbook Thunderbolt 3 Dock on Ubuntu

As mention in previously post, I installed Ubuntu on my HP ZBook. After two days used all things work just fine, but the Thunderbolt 3 Dock ...