<>Android 获取电池电量(广播获取和BatteryManager获取和执行命令获取)

<>方法一:注册广播(被动接受)
IntentFilter filter2 = new IntentFilter(); filter2.addAction(Intent.
ACTION_BATTERY_CHANGED); registerReceiver(filter2,receiver); 接收到广播后,用getIntExtra
("level")和getIntExtra("scale")获得相应值 intent.getIntExtra("level", 0); ///电池剩余电量
intent.getIntExtra("scale", 0); ///获取电池满电量数值 intent.getStringExtra("technology")
; ///获取电池技术支持 intent.getIntExtra("status",BatteryManager.BATTERY_STATUS_UNKNOWN)
; ///获取电池状态 intent.getIntExtra("plugged", 0); ///获取电源信息 intent.getIntExtra(
"health",BatteryManager.BATTERY_HEALTH_UNKNOWN); ///获取电池健康度 intent.getIntExtra(
"voltage", 0); ///获取电池电压 intent.getIntExtra("temperature", 0); ///获取电池温度
<>方法二:通过执行命令(不需要root)
通过 adb shell dumpsys battery,返回结果后有电池的各种信息,其中就包括level(百分比) C:\Users\ShawnXia>
adb shell dumpsys batteryCurrent Battery Service state: AC powered: false
///有线充电器状态 USB powered: true ///USB连接状态 Wireless powered: false ///无线充电状态 Max
charging current: 500000 ///最大充电电流,单位微安(uA) Max charging voltage: 5000000
///最大充电电压,单位微伏(uV) Charge counter: 4149000 /// status: 2
///充电状态,UNKNOWN=1,CHARGING=2,DISCHARGING=3,NOT_CHARGING=4,FULL=5 health: 2
///电池健康状态 present: true /// level: 95 ///当前95% scale: 100 ///满电100% voltage:
4244 ///电压 temperature: 250 ///温度 technology: Li-ion
<>方法三:通过 BatteryManager
API >= 21 (5.0,L) BatteryManager manager = (BatteryManager) getSystemService(
BATTERY_SERVICE); manager.getIntProperty(BatteryManager.
BATTERY_PROPERTY_CHARGE_COUNTER); manager.getIntProperty(BatteryManager.
BATTERY_PROPERTY_CURRENT_AVERAGE); manager.getIntProperty(BatteryManager.
BATTERY_PROPERTY_CURRENT_NOW); manager.getIntProperty(BatteryManager.
BATTERY_PROPERTY_CAPACITY);///当前电量百分比 API >= 26 (8.0,O) manager.getIntProperty(
BatteryManager.BATTERY_PROPERTY_STATUS);///充电状态

技术
今日推荐
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:766591547
关注微信