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

Thrift fails on Windows - thrift failed error: The command line is too long.

Meet a thrift compiling failure on my project on Windows 7. Using Maven in IntelliJ so I choiced maven-thrift-pluging for thrift files. For ...