本文转自:http://blog.sina.com.cn/s/blog_66a6a5ec0100n6ej.html
1.Java部分主要是BatteryService,作为电池及充电相关的服务,它的主要功能就是监听power_supply的uenvnt事件,读取sysfs中电池信息,然后通过intent广播给所有相关Activity。
源代码路径如下:
android_froyo/frameworks/base/services/java/com/android/server/BatteryService.java
BatteryService中实现了一个UEvent的观察者。uevent是Linux内核用来向用户空间主动上报事件的机制,对于JAVA程序来说,只实现UEventObserver的虚函数onUEvent,然后注册即可。
privateUEventObserver mUEventObserver = new UEventObserver() {
@Override
public void onUEvent(UEventObserver.UEvent event) {
update();
}
};
这里只关注power_supply的事件:
mUEventObserver.startObserving("SUBSYSTEM=power_supply");
当有power_supply相关的事件上报时,就会调用update函数。
update先调用native_update从sysfs中读取相关状态。
update然后根据读到的状态更新BatteryService的成员变量,并广播一个Intent来通知其它关注电源状态的组件。
<span style="font-family:Comic Sans MS;">private final void sendIntent() { // Pack up the values and broadcast them toeveryone Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); try { mBatteryStats.setOnBattery(mPlugType == BATTERY_PLUGGED_NONE,mBatteryLevel); } catch (RemoteException e) { // Should never happen. } int icon = getIcon(mBatteryLevel); intent.putExtra("status", mBatteryStatus); intent.putExtra("health", mBatteryHealth); intent.putExtra("present", mBatteryPresent); intent.putExtra("level", mBatteryLevel); ........... ActivityManagerNative.broadcastStickyIntent(intent, null); }</span>
<span style="font-family:Comic Sans MS;">static void android_server_BatteryService_update(JNIEnv* env,jobject obj) { setBooleanField(env, obj, gPaths.acOnlinePath,gFieldIds.mAcOnline); //... const int SIZE = 128; char buf[SIZE]; if(readFromFile(gPaths.batteryStatusPath, buf, SIZE) >0) env->SetIntField(obj, gFieldIds.mBatteryStatus,getBatteryStatus(buf)); else env->SetIntField(obj,gFieldIds.mBatteryStatus,gConstants.statusUnknown); if(readFromFile(gPaths.batteryHealthPath, buf, SIZE) >0) env->SetIntField(obj, gFieldIds.mBatteryHealth,getBatteryHealth(buf)); if(readFromFile(gPaths.batteryTechnologyPath, buf, SIZE)> 0) env->SetObjectField(obj,gFieldIds.mBatteryTechnology,env->NewStringUTF(buf)); } static JNINativeMethod sMethods[] = { {"native_update", "()V",(void*)android_server_BatteryService_update}, };</span>
/sys/class/power_supply/ac/online /sys/class/power_supply/ac/type /sys/class/power_supply/usb/online /sys/class/power_supply/usb/type /sys/class/power_supply/battery/status /sys/class/power_supply/battery/health /sys/class/power_supply/battery/present /sys/class/power_supply/battery/capacity /sys/class/power_supply/battery/batt_vol /sys/class/power_supply/battery/batt_temp /sys/class/power_supply/battery/technology /sys/class/power_supply/battery/type |