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

Android 從伺服器下載 APK 並安裝:流程與範例

編輯:關於 Android 程式設計

需求背景

許多 App 需要從伺服器取得更新檔,下載新的 APK 後引導使用者安裝。整個流程通常包含下載、保存、驗證與安裝四個步驟。

下載 APK

可使用 HttpURLConnection 建立連線,確認回應碼成功後,將輸入流寫入外部儲存空間。

URL url = new URL(apkUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);

if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
    InputStream inputStream = connection.getInputStream();
    FileOutputStream fileOutputStream = new FileOutputStream(apkFile);
    byte[] buffer = new byte[4096];
    int length;

    while ((length = inputStream.read(buffer)) != -1) {
        fileOutputStream.write(buffer, 0, length);
    }

    fileOutputStream.close();
    inputStream.close();
}

安裝 APK

下載完成後,可利用 Intent 開啟系統安裝流程。傳統寫法會指定 APK 的 MIME 類型。

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);

卸載應用

若要移除應用,可使用 ACTION_DELETE,並以 package: 加上完整套件名稱。

Uri packageUri = Uri.parse("package:com.demo.DUJINYANG");
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
startActivity(uninstallIntent);

實作建議

  • 下載行為應放在背景執行緒,避免阻塞 UI。
  • 需要確認網路權限與儲存空間權限。
  • 新版 Android 對未知來源安裝有較嚴格限制,通常需要宣告安裝未知應用權限。
  • 若使用 File URI 分享檔案,建議改用 FileProvider 以符合新版系統安全規範。
  • 下載完成後可先檢查檔案大小或雜湊值,再進入安裝流程。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved