編輯:關於 Android 程式設計
本文延續 MSM8909 平台的電池管理主題,聚焦在 Settings 應用中的 BatteryInfo 頁面——它是最直觀的電池狀態觀察窗口,也是排查底層問題的好入口。
先借用 MTK 的電池管理框架圖建立整體概念:

圖 1 電池管理框架
透過測試指令 *#*#4636#*#* 可以喚出 Testing 界面:

圖 2 Testing 界面
選擇 Battery information 進入詳情頁:

圖 3 電池資訊
此時若接上 USB 或 DC 充電,你會發現 Power plug 一欄顯示的是 Unknown。這說明底層上報的充電器類型本身就未被正確識別,需要往上追。要追這個問題,先讀懂 BatteryInfo 的實現。
對應源碼:packages/apps/Settings/src/com/android/settings/BatteryInfo.java
Activity 要能被啟動,必須先在清單中註冊。兩個屬性值得說明:
android:label
寫作 @string/battery_info_label,@ 表示引用資源,實際值在 res/values/strings.xml 中定義為 “Battery info”,也就是頁面標題。
android:taskAffinity
寫作 com.android.settings,表示這個 Activity 希望進入哪個 Task。
taskAffinity 描述的是 Activity 與 Task 之間的吸附關係。一般情況下,同一應用的 Activity 都在同一個 Task 中走完生命週期;但透過 taskAffinity,你可以讓某個 Activity 歸入另一個 Task。
規則是這樣的:每個 Activity 都有 taskAffinity 屬性,若未顯式指定,則繼承 Application 的設定;Application 也沒設定的話,預設值就是包名。而 Task 也有自己的 affinity,其值等於該 Task 根 Activity 的 taskAffinity。理解這層關係,後續處理 launchMode 與跳轉行為時會清楚很多。
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.battery_info);
// 建立 IntentFilter,用於監聽電池狀態廣播
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
}
三件事:載入布局(R.layout.battery_info 對應 res/layout/battery_info.xml);建立 IntentFilter;為它加上 ACTION_BATTERY_CHANGED 這個 action。這樣一來,任何發出帶有該 action 的 Intent 的元件,都會促使本頁刷新電池資訊。
public void onResume() {
super.onResume();
mStatus = (TextView) findViewById(R.id.status);
mPower = (TextView) findViewById(R.id.power);
mLevel = (TextView) findViewById(R.id.level);
mScale = (TextView) findViewById(R.id.scale);
mHealth = (TextView) findViewById(R.id.health);
mTechnology = (TextView) findViewById(R.id.technology);
mVoltage = (TextView) findViewById(R.id.voltage);
mTemperature = (TextView) findViewById(R.id.temperature);
mUptime = (TextView) findViewById(R.id.uptime);
mBatteryStats = IBatteryStats.Stub.asInterface(
ServiceManager.getService(BatteryStats.SERVICE_NAME));
mScreenStats = IPowerManager.Stub.asInterface(
ServiceManager.getService(POWER_SERVICE));
mHandler.sendEmptyMessageDelayed(EVENT_TICK, 3000);
registerReceiver(mIntentReceiver, mIntentFilter);
}
兩個驅動來源:一個是註冊的廣播接收者(被動,狀態變化時觸發);一個是 Handler 的定時消息(主動,週期性刷新)。
Handler 的實現
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case EVENT_TICK:
updateBatteryStats();
sendEmptyMessageDelayed(EVENT_TICK, 1000);
break;
}
}
};
收到 EVENT_TICK 後更新電池狀態,並在 1 秒後再發一次,形成循環。注意 onResume() 中首次發送延遲是 3000ms,之後改為 1000ms——開屏時留一點餘裕,之後進入穩定節奏。
廣播接收者
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
int plugType = intent.getIntExtra("plugged", 0);
mLevel.setText("" + intent.getIntExtra("level", 0));
mScale.setText("" + intent.getIntExtra("scale", 0));
mVoltage.setText("" + intent.getIntExtra("voltage", 0)
+ " " + getString(R.string.battery_info_voltage_units));
mTemperature.setText(""
+ tenthsToFixedString(intent.getIntExtra("temperature", 0))
+ getString(R.string.battery_info_temperature_units));
mTechnology.setText("" + intent.getStringExtra("technology"));
mStatus.setText(Utils.getBatteryStatus(getResources(), intent));
switch (plugType) {
case 0:
mPower.setText(getString(R.string.battery_info_power_unplugged));
break;
case BatteryManager.BATTERY_PLUGGED_AC:
mPower.setText(getString(R.string.battery_info_power_ac));
break;
case BatteryManager.BATTERY_PLUGGED_USB:
mPower.setText(getString(R.string.battery_info_power_usb));
break;
case BatteryManager.BATTERY_PLUGGED_WIRELESS:
mPower.setText(getString(R.string.battery_info_power_wireless));
break;
case (BatteryManager.BATTERY_PLUGGED_AC | BatteryManager.BATTERY_PLUGGED_USB):
mPower.setText(getString(R.string.battery_info_power_ac_usb));
break;
default:
mPower.setText(getString(R.string.battery_info_power_unknown));
break;
}
int health = intent.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
String healthString;
if (health == BatteryManager.BATTERY_HEALTH_GOOD) {
healthString = getString(R.string.battery_info_health_good);
} else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT) {
healthString = getString(R.string.battery_info_health_overheat);
} else if (health == BatteryManager.BATTERY_HEALTH_DEAD) {
healthString = getString(R.string.battery_info_health_dead);
} else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE) {
healthString = getString(R.string.battery_info_health_over_voltage);
} else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE) {
healthString = getString(R.string.battery_info_health_unspecified_failure);
} else if (health == BatteryManager.BATTERY_HEALTH_COLD) {
healthString = getString(R.string.battery_info_health_cold);
} else {
healthString = getString(R.string.battery_info_health_unknown);
}
mHealth.setText(healthString);
}
}
};
所有數值都直接從 Intent 的 extra 中讀取,這個 Intent 由 BatteryService 廣播出來。回到開頭的問題:plugType 之所以是 Unknown,是因為它一路從底層 BatteryService 傳上來時就已經是 0,界面層只是如實呈現。要修復必須往 kernel driver 或 HAL 層追。
充電狀態的特殊處理
Battery status 一欄沒有直接 switch,而是交給 Utils 統一封裝:
public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
final Intent intent = batteryChangedIntent;
int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
BatteryManager.BATTERY_STATUS_UNKNOWN);
String statusString;
if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
int resId;
if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
resId = R.string.battery_info_status_charging_ac;
} else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
resId = R.string.battery_info_status_charging_usb;
} else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
resId = R.string.battery_info_status_charging_wireless;
} else {
resId = R.string.battery_info_status_charging;
}
statusString = res.getString(resId);
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
statusString = res.getString(R.string.battery_info_status_discharging);
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
statusString = res.getString(R.string.battery_info_status_not_charging);
} else if (status == BatteryManager.BATTERY_STATUS_FULL) {
statusString = res.getString(R.string.battery_info_status_full);
} else {
statusString = res.getString(R.string.battery_info_status_unknown);
}
return statusString;
}
這裡的設計值得留意:充電狀態的文字會依「充電方式」細分為 AC / USB / 無線三種。所以當 plugType 異常時,即使 status 正確顯示為 Charging,也只會落到最泛用的那條字串,不會出現 USB 或 AC 的細分提示。這是排查充電器識別問題時的一個有用線索。
@Override
public void onPause() {
super.onPause();
mHandler.removeMessages(EVENT_TICK);
// 頁面不可見,停止 observer
unregisterReceiver(mIntentReceiver);
}
兩件事:移除定時消息,避免 Handler 繼續空轉;註銷廣播接收者,防止記憶體洩漏。這個「onResume 註冊、onPause 註銷」的配對是 Android 開發的基本紀律,任何動態註冊的接收者都必須遵守。
BatteryInfo 的實現模式很典型:被動監聽(廣播)加上主動輪詢(Handler)雙路驅動,資料來源則是 BatteryService 發出的 sticky broadcast。當你遇到「界面顯示不對」的問題,判斷策略是:先看界面層的 switch 分支是否齊全,再看 Intent extra 的值是否正確,最後才往 HAL 與 driver 層追——像本文開頭的 Power plug Unknown,就是第三層的問題。
Android ExpandableListView 控件使用教學
ExpandableListView 適合用來呈現具有層級結構的資料,例如群組與子項目。本文以一個簡易通訊錄為例,說明如何建立群組資料、子項資料,並透過自適配器完成畫面綁
Android 使用 Fragment 實現底部導航欄的實踐
效果說明 本文以 Fragment 為基礎,實作常見的底部導航欄。每個底部選項對應一個 Fragment,點擊後切換中央內容區域。 整體布局 畫面可分為三部分:頂部標
Android 圓角圖片產生方式
Android 中要讓 ImageView 顯示圓角圖,可先把 Bitmap 畫到 Canvas 上,並以 PorterDuff 模式裁切四個角。效能考量若圖片過大或数量
Android GridLayout 網格布局介紹
GridLayout 是 Android 4.0 之後加入的版面配置,適合用於建立網格狀畫面。它允許子元件跨行或跨列排列,適合用於計算機按鈕、圖示牆或需要對齊的介面。 G