Android 11 低电量自动关机
概述
安卓系统设计了低电关机功能,旨在当手机电池电量过低时自动关机,以保护手机硬件和数据安全。该功能由以下几个部分组成:
- 电池电量监测: 安卓系统通过 BatteryService 组件持续监测电池电量。BatteryService会从底层获取电池电量信息,并根据预设的阈值判断电池电量是否过低。
- 低电量警告: 当电池电量低于预设的警告阈值时,BatteryService会触发低电量警告。低电量警告通常会以弹窗或声音提示的形式通知用户。
- 低电关机: 当电池电量低于预设的关机阈值时,BatteryService会触发低电关机。低电关机前,系统会提示用户保存数据并关闭正在运行的应用。
基于RK3568 Android 11 系统开发过程中, 移植了电源和电池相关的驱动后, 测试发现低电自动关机的功能失效了.
分析
首先, 从dumpsys 中看下当前电池的一些状态信息(PS: 新版本的内容呈现有所不同):
-
dumpsys battery
battery Current Battery Service state: AC powered: false USB powered: false Wireless powered: false Max charging current: 0 Max charging voltage: 0 Charge counter: 0 status: 3 health: 2 present: true level: 0 scale: 100 voltage: 11 current: 640 temperature: 308 technology: Li-ion
-
处理低电关机的关键代码: frameworks/base/services/core/java/com/android/server/BatteryService.java
private void processValuesLocked(boolean force) { boolean logOutlier = false; long dischargeDuration = 0; mBatteryLevelCritical = mHealthInfo.batteryStatus != BatteryManager.BATTERY_STATUS_UNKNOWN && mHealthInfo.batteryLevel <= mCriticalBatteryLevel; if (mHealthInfo.chargerAcOnline) { mPlugType = BatteryManager.BATTERY_PLUGGED_AC; } else if (mHealthInfo.chargerUsbOnline) { mPlugType = BatteryManager.BATTERY_PLUGGED_USB; } else if (mHealthInfo.chargerWirelessOnline) { mPlugType = BatteryManager.BATTERY_PLUGGED_WIRELESS; } else { mPlugType = BATTERY_PLUGGED_NONE; } if (DEBUG) { Slog.d(TAG, "Processing new values: " + "info=" + mHealthInfo + ", mBatteryLevelCritical=" + mBatteryLevelCritical + ", mPlugType=" + mPlugType); } // Let the battery stats keep track of the current level. try { mBatteryStats.setBatteryState(mHealthInfo.batteryStatus, mHealthInfo.batteryHealth, mPlugType, mHealthInfo.batteryLevel, mHealthInfo.batteryTemperature, mHealthInfo.batteryVoltage, mHealthInfo.batteryChargeCounter, mHealthInfo.batteryFullCharge, mHealthInfo2p1.batteryChargeTimeToFullNowSeconds); } catch (RemoteException e) { // Should never happen. } shutdownIfNoPowerLocked(); shutdownIfOverTempLocked(); //.................... } private void shutdownIfNoPowerLocked() { // shut down gracefully if our battery is critically low and we are not powered. // wait until the system has booted before attempting to display the shutdown dialog. if (shouldShutdownLocked()) { mHandler.post(new Runnable() { @Override public void run() { if (mActivityManagerInternal.isSystemReady()) { Intent intent = new<