1. BatteryService.java(frameworks\base\services\java\com\android\server)
BatteryService是在系统启动的时候就跑起来的,(通过SystemServer.java可以看出)
电池的信息是实时的变化的,那如何能实时的更新电池的信息呢,
BatteryService会通过UEventObserver启动一个onEventThread
并会在构造函数中启动UEventObserver
mUEventObserver.startObserving("SUBSYSTEM=power_supply");
启动之后就不会停止,
然后会调用update()来更新电池的信息
Update()通过JNI来com_android_server_BatteryService.cpp(frameworks\base\services\jni) 读取数据,BatteryService通过JNI注册不仅是函数还有变量。
2. com_android_server_BatteryService.cpp(frameworks\base\services\jni)
在此函数中对status,healths,technology进行了读取
那还有其他的数据呢,是从哪里读取的呢,下面看一下
register_android_server_BatteryService()
3. register_android_server_BatteryService()(frameworks\base\services\jni)
此函数是在libandroid_servers.so被载入的时候,通过调用JNI_OnLoad()来调用的,
在此也可以看BatteryService需要的数据
(1). mAcOline 电源是连接方式是AC
(2). mUsbOnline 电源的连接方式是USB
(3). mBatteryStatus
(4). mBatteryHealth
(5). mBatteryPresent
(6). mBatteryLevel 电量的等级
(7). mBatteryTechnology 电池类型
(8). mBatteryVoltage 电压
(9).mBatteryTemperature 温度
BatteryStatus有5个状态,分别是:
public static final int BATTERY_STATUS_UNKNOWN = 1;
public static final int BATTERY_STATUS_CHARGING = 2;
public static final int BATTERY_STATUS_DISCHARGING =3;
public static final int BATTERY_STATUS_NOT_CHARGING =4;
public static final intBATTERY_STATUS_FULL = 5;
BatteryHealth有6个状态,分别是:
public static final int BATTERY_HEALTH_UNKNOWN= 1;
public static final intBATTERY_HEALTH_GOOD = 2;
public static final intBATTERY_HEALTH_OVERHEAT = 3;
public static final intBATTERY_HEALTH_DEAD = 4;
public static final intBATTERY_HEALTH_OVER_VOLTAGE = 5;
public static final intBATTERY_HEALTH_UNSPECIFIED_FAILURE = 6;
4. BatteryService是如何把数据传出去的
BatteryService通过Intent把数据传出去
说明:
mPlugType是链接的电源方式0 means it is on battery, other constants are different typesof power sources.)
BATTERY_SCALE 是电池的最大level
Icon integercontaining the resource ID of a small status bar icon indicating the current batterystate.
将所有的数据封装到Intent中,然后通过
ActivityManagerNative.broadcastStickyIntent(intent,null);
传出去。
5. 应用如何接收数据
应用如果想要接收到BatteryService发送出来的电池信息,则需要注册一个Intent为
Intent.ACTION_BATTERY_CHANGED的BroadcastReceiver
注册方法如下:
IntentFiltermIntentFilter = new IntentFilter(); mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED); registerReceiver(mIntentReciver,mIntentFilter); privateBroadcastReceiver mIntentReceiver = new BroadcastReceiver(){ @Override Public voidonReceive(Context context, Intent intent){ //TODO Auto-generated methodstub String action = intent.getAction(); If(action.equals(Intent.ACTION_BATTERY_CHANGED)){ int nVoltaget =intent.getIntExtra(“voltage”,0); if(nVoltage!=0){ mVoltage.setText(“v:”+ nVoltage + “mV-Success…”); } Else{ mVoltage.setText(“V:“+nVoltage+”mV-fall…”); } } } }