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

Android 以 root 權限靜默安裝 APK 的命令列實作

編輯:關於 Android 程式設計

本文說明如何利用 root 權限靜默安裝 APK、如何自動選擇「普通安裝」或「靜默安裝」,以及如何擴展 PackageUtils 來實作靜默解除安裝。

一、呼叫 root 靜默安裝

直接呼叫 PackageUtils.installSilent()。系統的權限管理會彈出對話框,詢問使用者是否允許應用取得 root 權限;一旦允許,後續即可靜默安裝。

該函式成功時回傳 PackageUtils.INSTALL_SUCCEEDED,失敗則回傳對應的錯誤碼,可以據此得知詳細原因——檔案不存在、apk 無效、系統空間不足、簽名不正確、缺少共用函式庫、share user 錯誤等等。

注意:較大的 apk 安裝過程非常耗時,務必另開執行緒呼叫,不要阻塞主執行緒。

二、靜默安裝的原理

PackageUtils.installSilent() 本質上就是執行 su 取得 root 後,再呼叫 pm install -r filePath。核心程式碼如下:

public class ShellUtils {

    public static final String COMMAND_SU       = "su";
    public static final String COMMAND_SH       = "sh";
    public static final String COMMAND_EXIT     = "exit\n";
    public static final String COMMAND_LINE_END = "\n";

    public static CommandResult execCommand(String[] commands,
                                            boolean isRoot,
                                            boolean isNeedResultMsg) {
        int result = -1;
        if (commands == null || commands.length == 0) {
            return new CommandResult(result, null, null);
        }

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;
        DataOutputStream os = null;

        try {
            process = Runtime.getRuntime().exec(isRoot ? COMMAND_SU : COMMAND_SH);
            os = new DataOutputStream(process.getOutputStream());

            for (String command : commands) {
                if (command == null) {
                    continue;
                }
                // 不要用 os.writeBytes(command),會有中文編碼問題
                os.write(command.getBytes());
                os.writeBytes(COMMAND_LINE_END);
                os.flush();
            }
            os.writeBytes(COMMAND_EXIT);
            os.flush();

            result = process.waitFor();

            if (isNeedResultMsg) {
                successMsg = new StringBuilder();
                errorMsg = new StringBuilder();
                successResult = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));
                errorResult = new BufferedReader(
                        new InputStreamReader(process.getErrorStream()));

                String s;
                while ((s = successResult.readLine()) != null) {
                    successMsg.append(s);
                }
                while ((s = errorResult.readLine()) != null) {
                    errorMsg.append(s);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) os.close();
                if (successResult != null) successResult.close();
                if (errorResult != null) errorResult.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }

        return new CommandResult(result,
                successMsg == null ? null : successMsg.toString(),
                errorMsg   == null ? null : errorMsg.toString());
    }
}

其中 commands 就是 pm install -r <path>。可見關鍵在於:先用 su 切換到 root 環境,再執行 pm install。

三、自動選擇安裝方式

PackageUtils 另外提供了 install(),它會依「是否為系統應用」以及「是否已取得 root」來決定要走哪一條路:

/**
 * install according conditions
 * if system application or rooted, see installSilent()
 * else see installNormal()
 */
public static final int install(Context context, String filePath) {
    if (!PackageUtils.isSystemApplication(context)) {
        boolean isRoot = ShellUtils.checkRootPermission();
        if (!isRoot) {
            return installNormal(context, filePath)
                    ? INSTALL_SUCCEEDED
                    : INSTALL_FAILED_INVALID_URI;
        }
    }
    return installSilent(context, filePath);
}

判斷邏輯是:非系統應用且未取得 root → 走普通安裝(跳系統安裝器);否則 → 走靜默安裝。這樣呼叫端就不必自己判斷環境。

四、擴展為靜默解除安裝

原理完全相同,把指令換成 pm uninstall [-k] PACKAGE 即可(-k 表示保留資料與快取目錄)。

五、幾個務必知道的限制

  • 需要 root:這整套做法的前提是裝置已解鎖並取得 root。在沒有 root 的一般裝置上,Runtime.exec("su") 會直接失敗,唯一能用的只有普通安裝(意圖跳安裝器)。
  • 「靜默」不等於「無聲」:首次執行 su 時,Superuser 管理器一定會跳出授權對話框。只有使用者先前已授予權限,後續才可能完全無感。
  • 不要把 su 當成常規方案:這是僅適用於企業內部 MDM、專用機櫃機、測試設備等受控情境的技巧。上架 Google Play 的應用若以此規避安裝流程,會直接違反政策。
  • 錯誤碼要處理:pm install 的 stderr 會帶出具體原因,建議完整記錄下來,否則線上遇到「少部分使用者裝不上」時無從追查。
  • 正式專案請改用 PackageInstaller:Android 5.0 以上提供 PackageInstaller.Session,可在不需 root 的前提下靜默安裝(仍需 REQUEST_INSTALL_PACKAGES 權限並引導使用者開啟「允許未知來源」)。這才是官方支援的路徑。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved