編輯:關於 Android 程式設計
手機的「系統更新」功能看似簡單,背後其實牽動了 Settings、廠商定制升級應用、RecoverySystem 以及 Recovery 模式等多個層次。本文先從上層應用的角度,把本地升級的完整呼叫鏈梳理清楚。
路徑是:設定 → 關於手機 → 系統更新。
這個「系統更新」條目由 DeviceInfoSettings.java 負責呈現,對應的 preference 定義在 Device_info_settings.xml 中:
<com.android.settings.xxupdatepreference
android:key="system_update_settings"
android:title="@string/system_update_settings_list_item_title"
android:summary="@string/system_update_settings_list_item_summary">
<intent android:action="android.settings.SYSTEM_UPDATE_SETTINGS" />
</com.android.settings.xxupdatepreference>
DeviceInfoSettings.java 對這個 preference 做監聽,使用者點擊時發出一個自定義廣播,由對應的升級應用接收並接手後續流程:
else if (preference.getKey().equals(KEY_DMSW_UPDATE)) {
Intent i = new Intent();
i.setAction(com.mediatek.DMSWUPDATE);
getActivity().sendBroadcast(i);
}
值得一提的是,Android 原生的 OTA 體驗相對樸素,因此市售機型的系統更新應用大多是廠商定制的。點擊後進入的通常是廠商自己的更新程式,這裡先跳過該環節,直接看本地升級的部分。
在廠商定制的更新應用中選擇「本地升級」,會先進入警告介面 SystemUpgradeChooserActivity.java,提示「升級過程中請勿移除電池、SIM 卡與記憶卡」,按下確定後再進入升級提醒介面。核心contirol邏輯如下:
case R.id.okButton:
// 是否掛載 SD Card
if (!hasSDCard()) {
showToast(R.string.no_sd_card);
return;
}
// 更新包是否存在
if (file == null || !file.exists()) {
showToast(R.string.no_update_file);
return;
}
// 進入升級提醒介面
Intent intent = new Intent(SystemUpgradeChooserActivity.this,
UpdateToStart.class);
startActivity(intent);
break;
接著在 UpdateToStart.java 中,使用者按下確定才真正開始安裝:
buttonOkUp.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 是否掛載 SD Card
if (!hasSDCard()) {
showToast(R.string.no_sd_card);
return;
}
// 更新檔案是否存在
File file = new File(Environment.getExternalStorageDirectory()
+ "/dload/update.zip");
if (file == null || !file.exists()) {
showToast(R.string.no_update_file);
return;
}
// 安裝更新包,這是上層系統調用的關鍵
RecoverySystem.installPackage(getApplicationContext(), file);
}
});
/**
* 為了安裝更新包將會重啟設備,此外要調用該方法需要在清單文件中
* 增加 REBOOT 權限。
* @param context 上下文
* @param packageFile 封裝更新包路徑等資訊的 File 物件
*/
public static void installPackage(Context context, File packageFile)
throws IOException {
String filename = packageFile.getCanonicalPath();
Log.w(TAG, "!!! REBOOTING TO INSTALL " + filename + " !!!");
// 參數拼接:這段字串最終會被寫入 BCB,
// 設備重啟進入 Recovery 模式後,Recovery.cpp 會解析該參數,
// 並依參數內容執行對應操作,它會被傳入 bootcommand(context, arg)
String arg = "--update_package=" + filename
+ "\n--locale=" + Locale.getDefault().toString();
bootCommand(context, arg);
}
也就是說,上層要做的事其實只有一件:把「要安裝哪個更新包」這個資訊寫進 BCB(Bootloader Control Block),然後重啟。真正的安裝動作,是重啟後由 Recovery 完成的。
private static void bootCommand(Context context, String arg)
throws IOException {
RECOVERY_DIR.mkdirs(); // 建立 /cache/recovery 目錄
COMMAND_FILE.delete(); // 刪除 command 檔,進行初始化
LOG_FILE.delete(); // 刪除 log 檔,進行初始化
Log.d(TAG, "Preapre to write command: " + arg);
WriteByFdSync(COMMAND_FILE, arg); // 將參數寫入 command 檔
Log.d(TAG, "Success to write command: " + arg);
Log.d(TAG, "Current build type is: " + Build.TYPE);
ReadInAndPrint(COMMAND_FILE); // 讀取 command 檔並印出 log
// 寫完 command 檔後,準備重啟
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
pm.reboot("recovery");
Log.d(TAG, "!!! pm.reboot failed !!!");
throw new IOException("Reboot failed (no permissions?)");
}
pm.reboot("recovery") 之後的呼叫鏈大致如下:
PowerManager.reboot(recovery) → PowerManagerService.reboot(reason) → PowerManagerService.shutdownOrRebootInternal(false, confirm, reason, wait) → ShutdownThread.reboot(mContext, reason, confirm) → ShutdownThread.run() 中的 running()。
@Override // Binder call
public void reboot(boolean confirm, String reason, boolean wait) {
mContext.enforceCallingOrSelfPermission(
android.Manifest.permission.REBOOT, null);
Slog.i(TAG, "reboot call pid: " + Binder.getCallingPid()
+ " uid: " + Binder.getCallingUid());
final long ident = Binder.clearCallingIdentity();
try {
shutdownOrRebootInternal(false, confirm, reason, wait);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private void shutdownOrRebootInternal(final boolean shutdown,
final boolean confirm, final String reason, boolean wait) {
if (mHandler == null || !mSystemReady) {
throw new IllegalStateException(
"Too early to call shutdown() or reboot()");
}
Runnable runnable = new Runnable() {
@Override
public void run() {
synchronized (this) {
if (shutdown) {
ShutdownThread.shutdown(mContext, confirm);
} else {
ShutdownThread.reboot(mContext, reason, confirm);
}
}
}
};
// ShutdownThread 必須在能顯示 UI 的 looper 上執行
Message msg = Message.obtain(mHandler, runnable);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
if (wait) {
synchronized (runnable) {
while (true) {
try {
runnable.wait();
} catch (InterruptedException e) {
// ignore
}
}
}
}
}
public static void reboot(final Context context, String reason,
boolean confirm) {
mReboot = true;
mRebootSafeMode = false;
mRebootReason = reason;
shutdownInner(context, confirm);
}
在 ShutdownThread 的 running() 方法中,重啟原因會被寫入系統屬性檔:
{
String reason = (mReboot ? "1" : "0")
+ (mRebootReason != null ? mRebootReason : "");
SystemProperties.set(SHUTDOWN_ACTION_PROPERTY, reason);
}
把上層流程串起來就是:Settings 發廣播 → 廠商升級應用接手 → 檢查 SD 卡與更新包 → RecoverySystem.installPackage 拼接參數 → bootCommand 寫入 /cache/recovery/command → PowerManager.reboot("recovery") 重啟 → 由 Recovery 根據 BCB 內容執行實際安裝。理解這條鏈之後,後續分析 Recovery 端如何解析參數、驗簽、寫入各分區就會清晰很多。
Android 開源菜單庫 SlidingMenu 深入剖析
SlidingMenu 簡介 SlidingMenu 是一種較新的側滑式介面設計,在主界面左滑或右滑即可唤出設定或功能頁面,操作直覺便利。目前已有大量應用採用,如 Eve
自定義 LinearLayout 與自定義 View 的兩種實現思路
自定義線性布局在項目中非常常用,本質上有兩條不同的路徑,理解它們的差別比記住語法更重要。 第一種:在擴展的 LinearLayout 構造方法中 Inflate 布局
Android ScrollView 快速返回頂部功能實作詳解
先看一下最終的實作效果: 這裡只示範了 ScrollView 返回頂部的核心功能,實際專案中可以替換圖示、隱藏右側滾動條等,UI 美化此處不贅述。 思路很直觀:當不在頂
Android 多執行緒與 Handler 的實用指南
當我們需要執行一些耗時操作時——比如發起一條網路請求——考慮到網速等種種因素,伺服器未必會立刻回應。如果不把這類操作放到子執行緒裡執行,就會導致主執行緒被阻塞,進而影響使