IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> 2022-06-09 分析Android11 Settings里面电池信息获取流程,在里面添加显示电池温度的功能。 -> 正文阅读

[移动开发]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

?

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-06-16 21:48:29  更:2022-06-16 21:49:14 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/25 2:38:42-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码