http://blog.chinaunix.net/uid-26926660-id-3329353.html
Android系統預設是電量為0關機的,如果要修改成還有5%電量就關機怎麼辦?(吐槽一下:其實修改成5%關機也沒什麼意義,因為即便還有電量,開機後系統也會再次被關閉),不過确實有這樣的需求,廢話少說,這裡簡單分析怎麼改:
2.分析
電池這一塊自然少不了Android BatteryService,在adb shell中敲入:
dumpsys battery
輸出如下:
Current Battery Service state:
AC powered: false
USB powered: true
status: 2
health: 2
present: true
level: 54
scale: 100
voltage:3856
temperature: 300
technology: LiFe
其中的level就是電量等級,temperature是攝氏溫度,不過少了小數點,是30度。BatteyService中決定關機的就兩個,一個level,一個temperature
mBatteryLevel,就是系統的電壓等級,最大值是SCALE,也就是100,修改後低電關機相關的代碼如下:
@./frameworks/base/services/java/com/android/server/BatteryService.java
- private final void shutdownIfNoPower() {
- // 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 (mBatteryLevel < 5 && !isPowered() && ActivityManagerNative.isSystemReady()) {
- Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
- intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- mContext.startActivity(intent);
- }
- }
- private final void shutdownIfOverTemp() {
- // shut down gracefully if temperature is too high (> 68.0C)
- // wait until the system has booted before attempting to display the shutdown dialog.
- if (mBatteryTemperature > 680 && ActivityManagerNative.isSystemReady()) {
- Intent intent = new Intent(Intent.ACTION_REQUEST_SHUTDOWN);
- intent.putExtra(Intent.EXTRA_KEY_CONFIRM, false);
- intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- mContext.startActivity(intent);
- }
- }
關機的原理是通過發送關機對話框的Intent來實作的,而不是調用ShutdownThread或是4.1的PowerManager
來實作的,這裡确實展現了Android的靈活之處。
關于BatteryService參數的更新,目前知道是通過uevent機制和sysfs進行互動更新的,這一塊還需要進一步跟進一下。