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

Android获取电池充电状态的方式

2017-11-14 13:58 519 查看
http://blog.csdn.net/manjianchao/article/details/78286151

我需要知道当前设备是否在充电,如何实现?

1、注册电池更改广播ACTION_BATTERY_CHANGED接收器。实现代码如下:
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
context.registerReceiver(this, filter);
..............

public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
int status=intent.getIntExtra("status",BatteryManager.BATTERY_STATUS_UNKNOWN);
if(status==BatteryManager.BATTERY_STATUS_CHARGING) {
//DoSomeThing
}
else {
//DoSomeThing
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

二、直接注册充电状态广播接收器
filter = new IntentFilter();
filter.addAction(BatteryManager.ACTION_CHARGING);
filter.addAction(BatteryManager.ACTION_DISCHARGING);
context.registerReceiver(this, filter);
..............

public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BatteryManager.ACTION_CHARGING)) {
//DoSomething
} else (action.equals(BatteryManager.ACTION_DISCHARGING)) {
//DoSomething
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

其实上面两种方式归结起来是一种方式。仔细分析一下这个两个广播在发送时候,就知道原因了。

frameworks/base/services/core/java/com/android/server/BatteryService.java#sendIntentLocked()
//  Pack up the values and broadcast them to everyone
final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
| Intent.FLAG_RECEIVER_REPLACE_PENDING);

int icon = getIconLocked(mBatteryProps.batteryLevel);

intent.putExtra(BatteryManager.EXTRA_STATUS, mBatteryProps.batteryStatus);//电池状态信息,可以在广播中直接获取当前电池的状态信息
intent.putExtra(BatteryManager.EXTRA_HEALTH, mBatteryProps.batteryHealth);
intent.putExtra(BatteryManager.EXTRA_PRESENT, mBatteryProps.batteryPresent);
intent.putExtra(BatteryManager.EXTRA_LEVEL, mBatteryProps.batteryLevel);//电量值
intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);//充电类型
intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mBatteryProps.batteryVoltage);
intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mBatteryProps.batteryTemperature);//电池温度
intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mBatteryProps.batteryTechnology);
intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_CURRENT, mBatteryProps.maxChargingCurrent);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: