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

Android 靜默安裝 APK 的實作

編輯:關於 Android 程式設計

靜默安裝需要系統權限,因此前提條件是手機已 root(若為系統應用並加入 INSTALL_PACKAGES 權限,則不需 root)。以下先說明一般安裝方式,再說明靜默安裝。

一、一般安裝

public static boolean installNormal(Context context, String filePath) {
    Intent i = new Intent(Intent.ACTION_VIEW);
    File file = new File(filePath);
    if (file == null || !file.exists() || !file.isFile() || file.length() <= 0) {
        return false;
    }
    i.setDataAndType(Uri.parse("file://" + filePath),
            "application/vnd.android.package-archive");
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);
    return true;
}

二、靜默安裝

靜默安裝的本質是透過 shell 執行 pm install 命令。核心方法如下:

public static int installSilent(Context context, String filePath) {
    return installSilent(context, filePath, "-r");
}

/**
 * 透過 root 靜默安裝套件。
 * 注意:不要在使用者介面執行緒呼叫,可能耗時。
 * 若為系統應用,需在 manifest 加入
 * android.permission.INSTALL_PACKAGES,則無需 root。
 *
 * @return INSTALL_SUCCEEDED 代表成功,其他值代表各種失敗原因
 */
public static int installSilent(Context context, String filePath, String pmParams) {
    if (filePath == null || filePath.length() == 0) {
        return INSTALL_FAILED_INVALID_URI;
    }
    File file = new File(filePath);
    if (file == null || file.length() <= 0 || !file.exists() || !file.isFile()) {
        return INSTALL_FAILED_INVALID_URI;
    }

    // 若為系統應用則不需 root,但需在 manifest 加入 INSTALL_PACKAGES 權限
    StringBuilder command = new StringBuilder()
            .append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install ")
            .append(pmParams == null ? "" : pmParams).append(" ")
            .append(filePath.replace(" ", "\\ "));
    CommandResult commandResult = DwShell.execCommand(command.toString(),
            !isSystemApplication(context), true);
    if (commandResult.successMsg != null
            && (commandResult.successMsg.contains("Success")
                || commandResult.successMsg.contains("success"))) {
        return INSTALL_SUCCEEDED;
    }

    // 依 errorMsg 內容判斷並回傳對應的失敗碼
    // 例如 INSTALL_FAILED_ALREADY_EXISTS、INSTALL_FAILED_INVALID_APK、
    // INSTALL_FAILED_INSUFFICIENT_STORAGE 等,此處省略逐一比對的細節
    return INSTALL_FAILED_OTHER;
}

其中執行的 shell 命令封裝如下:

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,避免中文編碼錯誤
            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());
}

關鍵在於:組出 pm install 命令後,透過 Runtime 執行 shell(必要時以 root 權限),再依命令輸出的成功訊息或錯誤訊息回傳對應的安裝結果碼。這樣便能對指定 APK 進行無互動的靜默安裝。

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