Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 本地升級原理與流程解析(一):上層應用視角

編輯:關於 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);
    }
});

四、RecoverySystem.installPackage 做了什麼

/**
 * 為了安裝更新包將會重啟設備,此外要調用該方法需要在清單文件中
 * 增加 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 完成的。

五、bootCommand 的細節

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 端如何解析參數、驗簽、寫入各分區就會清晰很多。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved