admin 管理员组文章数量: 887031
android电池循环 代码,Android获取电池充电状态的方式
我需要知道当前设备是否在充电,如何实现?
1、注册电池更改广播ACTION_BATTERY_CHANGED接收器。实现代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19IntentFilter 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
15filter = 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
}
}
其实上面两种方式归结起来是一种方式。仔细分析一下这个两个广播在发送时候,就知道原因了。
frameworks/base/services/core/java/com/android/server/BatteryService.java#sendIntentLocked()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19// 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);
本文标签: android电池循环 代码 Android获取电池充电状态的方式
版权声明:本文标题:android电池循环 代码,Android获取电池充电状态的方式 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.freenas.com.cn/free/1699479283h361836.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论