1.电池电量管理
Android的电量在Framework层都是以广播消息的形式发布的,发布者是BatteryService.java. BatteryService的原理就是利用UEventObserver的一个实例监测kernel层电量改变的事件。电量的驱动文件都放在/sys/class/power_supply目录下面,里面包括电压,电量百分比,AC/USB状态等信息。当电量改变时候JNI文件com_android_server_BatteryService.cpp会将/sys/class/power_supply里面的所有信息更新至BatteryService.java中
static void android_server_BatteryService_update(JNIEnv* env, jobject obj) { setBooleanField(env, obj, gPaths.acOnlinePath, gFieldIds.mAcOnline); setBooleanField(env, obj, gPaths.usbOnlinePath, gFieldIds.mUsbOnline); setBooleanField(env, obj, gPaths.batteryPresentPath, gFieldIds.mBatteryPresent); setIntField(env, obj, gPaths.batteryCapacityPath, gFieldIds.mBatteryLevel); setVoltageField(env, obj, gPaths.batteryVoltagePath, gFieldIds.mBatteryVoltage); setIntField(env, obj, gPaths.batteryTemperaturePath, gFieldIds.mBatteryTemperature); 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)); }
BatteryService再将电量信息以广播形式发布出去
private final void sendIntent() { // Pack up the values and broadcast them to everyone Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED); intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_REPLACE_PENDING); int icon = getIcon(mBatteryLevel); intent.putExtra(BatteryManager.EXTRA_STATUS, mBatteryStatus); intent.putExtra(BatteryManager.EXTRA_HEALTH, mBatteryHealth); intent.putExtra(BatteryManager.EXTRA_PRESENT, mBatteryPresent); intent.putExtra(BatteryManager.EXTRA_LEVEL, mBatteryLevel); 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, mBatteryVoltage); intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mBatteryTemperature); intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mBatteryTechnology); intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger); if (false) { Slog.d(TAG, "level:" + mBatteryLevel + " scale:" + BATTERY_SCALE + " status:" + mBatteryStatus + " health:" + mBatteryHealth + " present:" + mBatteryPresent + " voltage: " + mBatteryVoltage + " temperature: " + mBatteryTemperature + " technology: " + mBatteryTechnology + " AC powered:" + mAcOnline + " USB powered:" + mUsbOnline + " icon:" + icon + " invalid charger:" + mInvalidCharger); } ActivityManagerNative.broadcastStickyIntent(intent, null); }
Intent.ACTION_BATTERY_CHANGED的广播就可以获得所有电池状态信息