您的位置:首页 > 移动开发 > Android开发

Android 获取充电状态

2016-02-19 09:59 627 查看
[/code]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);  
}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: