Android获取手机电量和充电状态
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2018-06-10 14:02:32
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
取手机电量百分比
public static int getBattery(){ try { BatteryManager batteryManager = (BatteryManager) MyApplication.getContextObject().getSystemService(BATTERY_SERVICE); return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY); }catch (Exception e){ LogToFile.write(e); } return 0; }
取手机充电状态
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatusIntent = registerReceiver(null, ifilter); //如果设备正在充电,可以提取当前的充电状态和充电方式(无论是通过 USB 还是交流充电器),如下所示: // Are we charging / charged? int status = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL; // How are we charging? int chargePlug = batteryStatusIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; if (isCharging) { if (usbCharge) { Toast.makeText(MainActivity.this, "手机正处于USB连接!", Toast.LENGTH_SHORT).show(); } else if (acCharge) { Toast.makeText(MainActivity.this, "手机通过电源充电中!", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(MainActivity.this, "手机未连接USB线!", Toast.LENGTH_SHORT).show(); }