2022-06-09 分析Android11 Settings里面电池信息获取流程,在里面添加显示电池温度的功能。

一、AndroidR Settings 里面电池信息,显示电量百分比等,如下面的24%,那这个24%如何获取呢?

二、经过不停反复的分析,大致流程如下:

************************定时获取电池状态****************************
hardware\interfaces\health\utils\libhealthloop\HealthLoop.cpp
WakeAlarmEvent() -> PeriodicChores() ->ScheduleBatteryUpdate()


************************监测电池状态****************************
hardware\interfaces\health\utils\libhealth2impl\HalHealthLoop.cpp
ScheduleBatteryUpdate()
{
hardware\interfaces\health\utils\libhealth2impl\Health.cpp 
getHealthInfo_2_1 
system\core\healthd\BatteryMonitor.cpp  
updateValues()
} -> this->OnHealthInfoChanged(health_info)


************************发生信息到frameworks****************************
hardware\interfaces\health\utils\libhealth2impl\BinderHealth.cpp
OnHealthInfoChanged() -> Notify(health_info)

hardware\interfaces\health\utils\libhealth2impl\include\health2impl\Callback.h
Notify(const HealthInfo& info) ->healthInfoChanged_2_1(info)


************************发送电池信息广播****************************
frameworks\base\services\core\java\com\android\server\BatteryService.java
healthInfoChanged_2_1() -> update() ->processValuesLocked(false) -> sendBatteryChangedIntentLocked() -> broadcastStickyIntent()


************************Settings接收广播,在settings里面显示电池百分比****************************
packages\apps\Settings\src\com\android\settings\fuelgauge\BatteryBroadcastReceiver.java
onReceive()->
updateBatteryStatus(){
mBatteryListener.onBatteryChanged
}->
packages\apps\Settings\src\com\android\settings\fuelgauge\TopLevelBatteryPreferenceController.java
TopLevelBatteryPreferenceController()->updateState(mPreference)
->
packages\apps\Settings\src\com\android\settings\fuelgauge\BatteryHeaderPreferenceController.java
updateHeaderPreference()->
mBatteryPercentText.setText

三、添加显示电池温度的功能

1、涉及修改的文件 

2、涉及修改的文件内容如下


project frameworks/base/
diff --git a/services/core/java/com/android/server/BatteryService.java b/services/core/java/com/android/server/BatteryService.java
old mode 100644
new mode 100755
index 5cb52f7..17125d7
--- a/services/core/java/com/android/server/BatteryService.java
+++ b/services/core/java/com/android/server/BatteryService.java
@@ -118,7 +118,7 @@ import java.util.concurrent.atomic.AtomicReference;
 public final class BatteryService extends SystemService {
     private static final String TAG = BatteryService.class.getSimpleName();
 
-    private static final boolean DEBUG = false;
+    private static final boolean DEBUG = true;
 
     private static final int BATTERY_SCALE = 100;    // battery capacity is a percentage
 
@@ -146,6 +146,7 @@ public final class BatteryService extends SystemService {
     private final Object mLock = new Object();
 
     private HealthInfo mHealthInfo;
+	private int batteryLevel_number=28;
     private final HealthInfo mLastHealthInfo = new HealthInfo();
     private android.hardware.health.V2_1.HealthInfo mHealthInfo2p1;
     private boolean mBatteryLevelCritical;
@@ -324,6 +325,7 @@ public final class BatteryService extends SystemService {
         }
         mLowBatteryCloseWarningLevel = mLowBatteryWarningLevel + mContext.getResources().getInteger(
                 com.android.internal.R.integer.config_lowBatteryCloseWarningBump);
+		Slog.d(TAG, "updateBatteryWarningLevelLocked 1111 ");
         processValuesLocked(true);
     }
 
@@ -446,8 +448,13 @@ public final class BatteryService extends SystemService {
         synchronized (mLock) {
             if (!mUpdatesStopped) {
                 mHealthInfo = info.legacy.legacy;
+				batteryLevel_number++;
+			   // if(batteryLevel_number >80)
+				//	batteryLevel_number=28;
+				//mHealthInfo.batteryLevel = batteryLevel_number;
                 mHealthInfo2p1 = info;
                 // Process the new values.
+                Slog.d(TAG, "update  processValuesLocked");
                 processValuesLocked(false);
                 mLock.notifyAll(); // for any waiters on new info
             } else {
@@ -494,7 +501,7 @@ public final class BatteryService extends SystemService {
         }
 
         if (DEBUG) {
-            Slog.d(TAG, "Processing new values: "
+            Slog.d(TAG, "Processing new values:$$% "
                     + "info=" + mHealthInfo
                     + ", mBatteryLevelCritical=" + mBatteryLevelCritical
                     + ", mPlugType=" + mPlugType);
@@ -508,7 +515,6 @@ public final class BatteryService extends SystemService {
                     mHealthInfo.batteryFullCharge,
                     mHealthInfo2p1.batteryChargeTimeToFullNowSeconds);
         } catch (RemoteException e) {
-            // Should never happen.
         }
 
         shutdownIfNoPowerLocked();
@@ -670,8 +676,8 @@ public final class BatteryService extends SystemService {
             // them will get the new sequence number at that point.  (See for example how testing
             // of JobScheduler's BatteryController works.)
             sendBatteryChangedIntentLocked();
-            if (mLastBatteryLevel != mHealthInfo.batteryLevel || mLastPlugType != mPlugType) {
-                sendBatteryLevelChangedIntentLocked();
+            if (mLastBatteryLevel != mHealthInfo.batteryLevel || mLastBatteryTemperature != mHealthInfo.batteryTemperature || mLastPlugType != mPlugType) {
+                //sendBatteryLevelChangedIntentLocked();
             }
 
 
@@ -770,6 +776,7 @@ public final class BatteryService extends SystemService {
         final Intent intent = new Intent(Intent.ACTION_BATTERY_LEVEL_CHANGED);
         intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
         intent.putParcelableArrayListExtra(BatteryManager.EXTRA_EVENTS, events);
+		Slog.e(TAG, "sendEnqueuedBatteryLevelChangedEvents uuuuuuuuuuu");
 
         mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
                 android.Manifest.permission.BATTERY_STATS);
@@ -1015,6 +1022,7 @@ public final class BatteryService extends SystemService {
     }
 
     private void processValuesFromShellLocked(PrintWriter pw, int opts) {
+        Slog.d(TAG, "processValuesFromShellLocked 00000 ");
         processValuesLocked((opts & OPTION_FORCE_UPDATE) != 0);
         if ((opts & OPTION_FORCE_UPDATE) != 0) {
             pw.println(mSequence);
@@ -1160,6 +1168,7 @@ public final class BatteryService extends SystemService {
         }
 
         @Override public void healthInfoChanged_2_1(android.hardware.health.V2_1.HealthInfo props) {
+        	Slog.d(TAG, "healthInfoChanged_2_1 -> update");
             BatteryService.this.update(props);
         }
 

project hardware/interfaces/
diff --git a/health/utils/libhealth2impl/BinderHealth.cpp b/health/utils/libhealth2impl/BinderHealth.cpp
old mode 100644
new mode 100755
index 625d0e0..395f9fc
--- a/health/utils/libhealth2impl/BinderHealth.cpp
+++ b/health/utils/libhealth2impl/BinderHealth.cpp
@@ -76,6 +76,7 @@ Return<Result> BinderHealth::registerCallback(const sp<V2_0::IHealthInfoCallback
             LOG(ERROR) << "Cannot call getHealthInfo_2_1: " << toString(res);
             return;
         }
+		LOG(ERROR) << "BinderHealth" << "registerCallback Notify";
         auto ret = wrapped->Notify(health_info);
         if (IsDeadObjectLogged(ret)) {
             // Remove callback reference.
@@ -119,6 +120,7 @@ Return<Result> BinderHealth::update() {
             result = res;
             return;
         }
+		LOG(ERROR) << "BinderHealth" << " update";
         OnHealthInfoChanged(health_info);
     });
     return result;
@@ -132,6 +134,7 @@ void BinderHealth::OnHealthInfoChanged(const HealthInfo& health_info) {
     // Notify all callbacks
     std::unique_lock<decltype(callbacks_lock_)> lock(callbacks_lock_);
     for (auto it = callbacks_.begin(); it != callbacks_.end();) {
+		LOG(ERROR) << "BinderHealth" << " OnHealthInfoChanged Notify";
         auto ret = (*it)->Notify(health_info);
         if (IsDeadObjectLogged(ret)) {
             it = callbacks_.erase(it);
diff --git a/health/utils/libhealth2impl/HalHealthLoop.cpp b/health/utils/libhealth2impl/HalHealthLoop.cpp
old mode 100644
new mode 100755
index 3901a76..80b5114
--- a/health/utils/libhealth2impl/HalHealthLoop.cpp
+++ b/health/utils/libhealth2impl/HalHealthLoop.cpp
@@ -59,6 +59,7 @@ void HalHealthLoop::Heartbeat(void) {
 void HalHealthLoop::ScheduleBatteryUpdate() {
     // ignore errors. impl may not be able to handle any callbacks, so
     // update() may return errors.
+    LOG(ERROR) << "HalHealthLoop" << " ScheduleBatteryUpdate service_->update";
     Result res = service_->update();
     if (res != Result::SUCCESS) {
         LOG(WARNING) << "update() on the health HAL implementation failed with " << toString(res);
@@ -68,6 +69,8 @@ void HalHealthLoop::ScheduleBatteryUpdate() {
         CHECK(res == Result::SUCCESS)
                 << "getHealthInfo_2_1() on the health HAL implementation failed with "
                 << toString(res);
+		
+		LOG(ERROR) << "HalHealthLoop" << " ScheduleBatteryUpdate OnHealthInfoChanged";
         this->OnHealthInfoChanged(health_info);
     });
 }
diff --git a/health/utils/libhealth2impl/Health.cpp b/health/utils/libhealth2impl/Health.cpp
old mode 100644
new mode 100755
index f4684ae..25151f6
--- a/health/utils/libhealth2impl/Health.cpp
+++ b/health/utils/libhealth2impl/Health.cpp
@@ -80,6 +80,7 @@ Return<Result> Health::unregisterCallback(const sp<V2_0::IHealthInfoCallback>&)
 
 Return<Result> Health::update() {
     Result result = Result::UNKNOWN;
+	LOG(ERROR) << "Health::update getHealthInfo_2_1 logValues";
     getHealthInfo_2_1([&](auto res, const auto& /* health_info */) {
         result = res;
         if (res != Result::SUCCESS) {
diff --git a/health/utils/libhealthloop/HealthLoop.cpp b/health/utils/libhealthloop/HealthLoop.cpp
old mode 100644
new mode 100755
index 3f4b5bc..6dcb9e4
--- a/health/utils/libhealthloop/HealthLoop.cpp
+++ b/health/utils/libhealthloop/HealthLoop.cpp
@@ -176,7 +176,7 @@ void HealthLoop::WakeAlarmEvent(uint32_t /*epevents*/) {
         KLOG_ERROR(LOG_TAG, "wakealarm_event: read wakealarm fd failed\n");
         return;
     }
-
+	KLOG_ERROR(LOG_TAG, "WakeAlarmEvent PeriodicChores\n");
     PeriodicChores();
 }
 
diff --git a/health/utils/libhealthloop/utils.cpp b/health/utils/libhealthloop/utils.cpp
old mode 100644
new mode 100755
index cd8c7a9..9357198
--- a/health/utils/libhealthloop/utils.cpp
+++ b/health/utils/libhealthloop/utils.cpp
@@ -20,7 +20,7 @@ namespace hardware {
 namespace health {
 
 // Periodic chores fast interval in seconds
-#define DEFAULT_PERIODIC_CHORES_INTERVAL_FAST (60 * 1)
+#define DEFAULT_PERIODIC_CHORES_INTERVAL_FAST (5 * 1)
 // Periodic chores fast interval in seconds
 #define DEFAULT_PERIODIC_CHORES_INTERVAL_SLOW (60 * 10)
 

project packages/apps/Settings/
diff --git a/src/com/android/settings/fuelgauge/BatteryBroadcastReceiver.java b/src/com/android/settings/fuelgauge/BatteryBroadcastReceiver.java
old mode 100644
new mode 100755
index 71e65bf..47f5fc4
--- a/src/com/android/settings/fuelgauge/BatteryBroadcastReceiver.java
+++ b/src/com/android/settings/fuelgauge/BatteryBroadcastReceiver.java
@@ -75,6 +75,7 @@ public class BatteryBroadcastReceiver extends BroadcastReceiver {
 
     @VisibleForTesting
     String mBatteryLevel;
+    int mBatterytemperature;
     @VisibleForTesting
     String mBatteryStatus;
     @VisibleForTesting
@@ -88,6 +89,7 @@ public class BatteryBroadcastReceiver extends BroadcastReceiver {
 
     @Override
     public void onReceive(Context context, Intent intent) {
+        Log.e(TAG, "onReceive updateBatteryStatus ");
         updateBatteryStatus(intent, false /* forceUpdate */);
     }
 
@@ -112,9 +114,15 @@ public class BatteryBroadcastReceiver extends BroadcastReceiver {
         if (intent != null && mBatteryListener != null) {
             if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                 final String batteryLevel = Utils.getBatteryPercentage(intent);
+				final int batterytemperature = intent.getIntExtra(
+                        BatteryManager.EXTRA_TEMPERATURE, 0);//EXTRA_TEMPERATURE
                 final String batteryStatus = Utils.getBatteryStatus(mContext, intent);
                 final int batteryHealth = intent.getIntExtra(
                         BatteryManager.EXTRA_HEALTH, BatteryManager.BATTERY_HEALTH_UNKNOWN);
+
+
+             Log.e(TAG, "onReceive  updateBatteryStatus  batterytemperature="+batterytemperature+" mBatterytemperature="+mBatterytemperature);
+						
                 if (!Utils.isBatteryPresent(intent)) {
                     Log.w(TAG, "Problem reading the battery meter.");
                     mBatteryListener.onBatteryChanged(BatteryUpdateType.BATTERY_NOT_PRESENT);
@@ -122,12 +130,15 @@ public class BatteryBroadcastReceiver extends BroadcastReceiver {
                     mBatteryListener.onBatteryChanged(BatteryUpdateType.MANUAL);
                 } else if (batteryHealth != mBatteryHealth) {
                     mBatteryListener.onBatteryChanged(BatteryUpdateType.BATTERY_HEALTH);
-                } else if(!batteryLevel.equals(mBatteryLevel)) {
+                } else if(!batteryLevel.equals(mBatteryLevel) || batterytemperature !=mBatterytemperature) {
                     mBatteryListener.onBatteryChanged(BatteryUpdateType.BATTERY_LEVEL);
+					Log.e(TAG, "mBatteryListener.onBatteryChanged  9666  ");
+			
                 } else if (!batteryStatus.equals(mBatteryStatus)) {
                     mBatteryListener.onBatteryChanged(BatteryUpdateType.BATTERY_STATUS);
                 }
                 mBatteryLevel = batteryLevel;
+				mBatterytemperature = batterytemperature;
                 mBatteryStatus = batteryStatus;
                 mBatteryHealth = batteryHealth;
             } else if (PowerManager.ACTION_POWER_SAVE_MODE_CHANGED.equals(intent.getAction())) {
diff --git a/src/com/android/settings/fuelgauge/BatteryHeaderPreferenceController.java b/src/com/android/settings/fuelgauge/BatteryHeaderPreferenceController.java
old mode 100644
new mode 100755
index 11d7564..173abbf
--- a/src/com/android/settings/fuelgauge/BatteryHeaderPreferenceController.java
+++ b/src/com/android/settings/fuelgauge/BatteryHeaderPreferenceController.java
@@ -47,6 +47,7 @@ import com.android.settingslib.core.lifecycle.Lifecycle;
 import com.android.settingslib.core.lifecycle.LifecycleObserver;
 import com.android.settingslib.core.lifecycle.events.OnStart;
 import com.android.settingslib.widget.LayoutPreference;
+import android.util.Slog;
 
 /**
  * Controller that update the battery header view
@@ -57,6 +58,7 @@ public class BatteryHeaderPreferenceController extends BasePreferenceController
     @VisibleForTesting
     static final String KEY_BATTERY_HEADER = "battery_header";
     private static final String ANNOTATION_URL = "url";
+	private String TAG = "BatteryHeaderPreferenceController";
 
     @VisibleForTesting
     BatteryStatusFeatureProvider mBatteryStatusFeatureProvider;
@@ -133,7 +135,8 @@ public class BatteryHeaderPreferenceController extends BasePreferenceController
     }
 
     public void updateHeaderPreference(BatteryInfo info) {
-        mBatteryPercentText.setText(formatBatteryPercentageText(info.batteryLevel));
+        Slog.e(TAG, "updateHeaderPreference setText!");
+        mBatteryPercentText.setText(formatBatteryPercentageText(info.batteryLevel)+ "  "+info.batteryTemperature+"℃");//000000
         if (!mBatteryStatusFeatureProvider.triggerBatteryStatusUpdate(this, info)) {
             mSummary1.setText(generateLabel(info));
         }
@@ -154,6 +157,7 @@ public class BatteryHeaderPreferenceController extends BasePreferenceController
         Intent batteryBroadcast = mContext.registerReceiver(null,
                 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
         final int batteryLevel = Utils.getBatteryLevel(batteryBroadcast);
+		final int batteryTemperature = batteryBroadcast.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
         final boolean discharging =
                 batteryBroadcast.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) == 0;
 
@@ -161,7 +165,9 @@ public class BatteryHeaderPreferenceController extends BasePreferenceController
         mBatteryMeterView.setBatteryLevel(batteryLevel);
         mBatteryMeterView.setCharging(!discharging);
         mBatteryMeterView.setPowerSave(mPowerManager.isPowerSaveMode());
-        mBatteryPercentText.setText(formatBatteryPercentageText(batteryLevel));
+		Slog.e(TAG, "quickUpdateHeaderPreference setText!");
+        //mBatteryPercentText.setText(formatBatteryPercentageText(batteryLevel));
+		mBatteryPercentText.setText(formatBatteryPercentageText(batteryLevel)+ "  "+batteryTemperature+"℃");
     }
 
     @VisibleForTesting
diff --git a/src/com/android/settings/fuelgauge/BatteryInfo.java b/src/com/android/settings/fuelgauge/BatteryInfo.java
old mode 100644
new mode 100755
index 49bdcbb..93e097c
--- a/src/com/android/settings/fuelgauge/BatteryInfo.java
+++ b/src/com/android/settings/fuelgauge/BatteryInfo.java
@@ -44,6 +44,7 @@ public class BatteryInfo {
     public CharSequence chargeLabel;
     public CharSequence remainingLabel;
     public int batteryLevel;
+	public int batteryTemperature;
     public boolean discharging = true;
     public boolean isOverheated;
     public long remainingTimeUs = 0;
@@ -230,6 +231,7 @@ public class BatteryInfo {
         BatteryInfo info = new BatteryInfo();
         info.mStats = stats;
         info.batteryLevel = Utils.getBatteryLevel(batteryBroadcast);
+        info.batteryTemperature = batteryBroadcast.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
         info.batteryPercentString = Utils.formatPercentage(info.batteryLevel);
         info.mCharging = batteryBroadcast.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
         info.averageTimeToDischarge = estimate.getAverageDischargeTime();
diff --git a/src/com/android/settings/fuelgauge/PowerUsageSummary.java b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
old mode 100644
new mode 100755
index 57949db..e251274
--- a/src/com/android/settings/fuelgauge/PowerUsageSummary.java
+++ b/src/com/android/settings/fuelgauge/PowerUsageSummary.java
@@ -52,6 +52,7 @@ import com.android.settingslib.search.SearchIndexable;
 import com.android.settingslib.utils.PowerUtil;
 import com.android.settingslib.utils.StringUtil;
 import com.android.settingslib.widget.LayoutPreference;
+import android.util.Slog;
 
 import java.util.List;
 
@@ -117,6 +118,7 @@ public class PowerUsageSummary extends PowerUsageBase implements OnLongClickList
 
                 @Override
                 public void onLoadFinished(Loader<BatteryInfo> loader, BatteryInfo batteryInfo) {
+                    Slog.e("BatteryInfo", " onLoadFinished updateHeaderPreference");
                     mBatteryHeaderPreferenceController.updateHeaderPreference(batteryInfo);
                     mBatteryInfo = batteryInfo;
                     updateLastFullChargePreference();
@@ -389,6 +391,7 @@ public class PowerUsageSummary extends PowerUsageBase implements OnLongClickList
         super.restartBatteryStatsLoader(refreshType);
         // Update battery header if battery is present.
         if (mIsBatteryPresent) {
+			     Slog.e("BatteryInfo", "restartBatteryStatsLoader quickUpdateHeaderPreference");
             mBatteryHeaderPreferenceController.quickUpdateHeaderPreference();
         }
     }

3、查看更新电池信息时候的log

 4、电池温度在settings里面有显示了,欧耶

 5、特别记录一下,原本sdk默认是60s 去读底层更新一下电池信息,我嫌太慢,这里为了方便测试,改为5s 更新一次,修改的代码在

hardware\interfaces\health\utils\libhealthloop\utils.cpp

猜你喜欢

转载自blog.csdn.net/qq_37858386/article/details/125205834
今日推荐