- IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
- Intent batteryStatus = this.registerReceiver(null, filter);
- int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
- boolean acCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC);
- if (acCharge) {
- Log.v(LOG_TAG,“The phone is charging!”);
- }
- /**
- * This method checks for power by comparing the current battery state against all possible
- * plugged in states. In this case, a device may be considered plugged in either by USB, AC, or
- * wireless charge. (Wireless charge was introduced in API Level 17.)
- */
- private boolean checkForPower() {
- // It is very easy to subscribe to changes to the battery state, but you can get the current
- // state by simply passing null in as your receiver. Nifty, isn't that?
- IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
- Intent batteryStatus = this.registerReceiver(null, filter);
- // There are currently three ways a device can be plugged in. We should check them all.
- int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
- boolean usbCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_USB);
- boolean acCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_AC);
- boolean wirelessCharge = false;
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
- wirelessCharge = (chargePlug == BatteryManager.BATTERY_PLUGGED_WIRELESS);
- }
- return (usbCharge || acCharge || wirelessCharge);
- }
Android 获取充电状态
最新推荐文章于 2024-07-07 11:09:08 发布
