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

Android 版本更新全流程:檢查更新、下載 APK 與安裝

編輯:關於 Android 程式設計

這個實例取自一個天氣預報 App 的更新模組,把「檢查版本 → 提示使用者 → 下載 APK → 觸發安裝」整條鏈路串了起來,同時處理了幾個容易被忽略的細節:SD 卡是否掛載、檔案大小格式化、下載中斷與取消、網路異常提示,以及「已是最新版本」的告知。

整體結構

DownloadManager 以單例形式存在,內部用 Handler 在多個狀態之間切換,對應的訊息常數如下:

private static final int DOWN_NOSDCARD = 0;   // 未掛載 SD 卡
private static final int DOWN_UPDATE   = 1;   // 下載進度更新
private static final int DOWN_OVER     = 2;   // 下載完成
private static final int DOWN_ERROR    = 3;   // 下載失敗

private static final int DIALOG_TYPE_LATEST        = 0;  // 已是最新
private static final int DIALOG_TYPE_FAIL          = 1;  // 抓不到版本資訊
private static final int DIALOG_TYPE_INTERNETERROR = 2;  // 網路故障

一、取得單例並啟動下載

private static DownloadManager downloadManager;

public static DownloadManager getDownloadManager() {
    if (downloadManager == null) {
        downloadManager = new DownloadManager();
    }
    downloadManager.interceptFlag = false;   // 重設取消旗標
    return downloadManager;
}

public void DownLoader(Context context, AppDetail download) {
    this.mContext = context;
    this.mDownload = download;
    showDownloadDialog();
}

二、檢查 App 更新

做法是先讀取本機版本資訊,再開一條子線程去抓遠端 update.xml,解析成 AppDetail 物件後回傳主線程比對 versionCode。

public void checkAppUpdate(Context context, final boolean isShowMsg, final boolean notmain) {
    this.mContext = context;
    getCurrentVersion(mContext);

    if (isShowMsg) {
        if (mProDialog == null) {
            mProDialog = ProgressDialog.show(mContext, null, "正在檢測,請稍後...", true, true);
        } else if (mProDialog.isShowing()
                || (latestOrFailDialog != null && latestOrFailDialog.isShowing())) {
            return;   // 已有提示在顯示,避免重複彈出
        }
    }

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (mProDialog != null && !mProDialog.isShowing()) {
                return;   // 進度框已關閉,連結果也不必顯示
            }
            if (isShowMsg && mProDialog != null) {
                mProDialog.dismiss();
                mProDialog = null;
            }

            if (msg.what == 1) {
                mDownload = (AppDetail) msg.obj;
                if (mDownload != null && curVersionCode < mDownload.getVersionCode()) {
                    apkUrl = mDownload.getUri() + mDownload.getFileName();
                    updateMsg = mDownload.getAppHistory();
                    showNoticeDialog();
                } else if (isShowMsg && notmain) {
                    showLatestOrFailDialog(DIALOG_TYPE_LATEST);
                }
            } else if (msg.what == -1 && isShowMsg) {
                showLatestOrFailDialog(DIALOG_TYPE_INTERNETERROR);
            } else if (isShowMsg) {
                showLatestOrFailDialog(DIALOG_TYPE_FAIL);
            }
        }
    };

    new Thread() {
        public void run() {
            Message msg = new Message();
            try {
                DefaultHttpClient client = new DefaultHttpClient();
                client.getParams().setParameter(
                        CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
                HttpGet get = new HttpGet(checkUrl);
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream stream = new ByteArrayInputStream(
                            EntityUtils.toString(entity, "gb2312").getBytes());
                    msg.what = 1;
                    msg.obj = AppDetail.parseXML(stream);
                } else {
                    msg.what = -1;
                }
            } catch (Exception e) {
                e.printStackTrace();
                msg.what = -1;
            }
            handler.sendMessage(msg);
        }
    }.start();
}

三、讀取本機版本資訊

public String getCurrentVersion(Context context) {
    try {
        PackageInfo info = context.getPackageManager()
                .getPackageInfo(context.getPackageName(), 0);
        curVersionName = info.versionName;
        curVersionCode = info.versionCode;
    } catch (NameNotFoundException e) {
        e.printStackTrace(System.err);
    }
    return curVersionName;
}

四、提示與下載對話框

「已是最新版本」、「無法獲取版本資訊」、「網路故障」三種情境共用一個方法,只是文案不同;這裡用 Toast 呈現,避免連續彈窗打斷使用者。

private void showLatestOrFailDialog(int dialogType) {
    String ToastMsg = "";
    if (latestOrFailDialog != null) {
        latestOrFailDialog.dismiss();
        latestOrFailDialog = null;
    }
    if (dialogType == DIALOG_TYPE_LATEST) {
        ToastMsg = "您當前已經是最新版本";
    } else if (dialogType == DIALOG_TYPE_FAIL) {
        ToastMsg = "無法獲取版本更新信息";
    } else if (dialogType == DIALOG_TYPE_INTERNETERROR) {
        ToastMsg = "網絡故障,無法連接服務器";
    }
    Toast.makeText(mContext, ToastMsg, Toast.LENGTH_SHORT).show();
}

/** 版本更新通知對話框 */
private void showNoticeDialog() {
    AlertDialog.Builder builder = new Builder(mContext);
    builder.setTitle("軟件版本更新");
    builder.setMessage(updateMsg);
    builder.setPositiveButton("立即更新", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            showDownloadDialog();
        }
    });
    builder.setNegativeButton("以後再說", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    noticeDialog = builder.create();
    noticeDialog.show();
}

/** 下載對話框:內含自訂的進度條與文字佈局 */
private void showDownloadDialog() {
    AlertDialog.Builder builder = new Builder(mContext);
    builder.setTitle("正在下載安裝包");
    View v = LayoutInflater.from(mContext).inflate(R.layout.download_progress, null);
    mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
    mProgressText = (TextView) v.findViewById(R.id.update_progress_text);
    builder.setView(v);
    builder.setNegativeButton("取消", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            interceptFlag = true;      // 通知下載迴圈收工
        }
    });
    builder.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            dialog.dismiss();
            interceptFlag = true;
        }
    });
    downloadDialog = builder.create();
    downloadDialog.setCanceledOnTouchOutside(false);   // 點外部不關閉,避免誤觸中斷
    downloadDialog.show();
    downloadApk();
}

五、下載與安裝

下載策略是先寫成 .tmp 暫存檔,全部完成後再用 renameTo 轉為 .apk,如此一來即使中途斷網,也不會留下一個看似完整卻其實半截的安裝檔。

private Runnable mdownApkRunnable = new Runnable() {
    Message error_msg = new Message();

    @Override
    public void run() {
        try {
            String apkName = mDownload.getFileName().replace(".apk", "") + ".apk";
            String tmpApk  = mDownload.getFileName().replace(".apk", "") + ".tmp";

            // 確認 SD 卡是否掛載
            String storageState = Environment.getExternalStorageState();
            if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                savePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/QN/QNStore/";
                File dir = new File(savePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                apkFilePath = savePath + apkName;
                tmpFilePath = savePath + tmpApk;
            }
            if (apkFilePath == null || apkFilePath == "") {
                mHandler.sendEmptyMessage(DOWN_NOSDCARD);
                return;
            }

            File ApkFile = new File(apkFilePath);
            File tmpFile = new File(tmpFilePath);
            FileOutputStream fos = new FileOutputStream(tmpFile);

            URL url = new URL(mDownload.getUri() + mDownload.getFileName());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            try {
                conn.connect();
            } catch (ConnectTimeoutException e) {
                error_msg.what = DOWN_ERROR;
                error_msg.arg1 = 0;
                mHandler.sendMessage(error_msg);
            }

            int length = conn.getContentLength();
            InputStream is = conn.getInputStream();

            // 檔案大小以兩位小數的 MB 呈現
            DecimalFormat df = new DecimalFormat("0.00");
            apkFileSize = df.format((float) length / 1024 / 1024) + "MB";

            int count = 0;
            byte buf[] = new byte[1024];
            do {
                int numread = is.read(buf);
                count += numread;
                tmpFileSize = df.format((float) count / 1024 / 1024) + "MB";
                progress = (int) (((float) count / length) * 100);
                mHandler.sendEmptyMessage(DOWN_UPDATE);

                if (numread <= 0) {
                    // 讀完了,把暫存檔轉成正式 APK 再通知安裝
                    if (tmpFile.renameTo(ApkFile)) {
                        mHandler.sendEmptyMessage(DOWN_OVER);
                    }
                    break;
                }
                fos.write(buf, 0, numread);
            } while (!interceptFlag);      // 使用者按取消就跳出

            fos.close();
            is.close();
        } catch (MalformedURLException e) {
            error_msg.what = DOWN_ERROR;
            error_msg.arg1 = 1;
            mHandler.sendMessage(error_msg);
        } catch (IOException e) {
            error_msg.what = DOWN_ERROR;
            error_msg.arg1 = 2;
            mHandler.sendMessage(error_msg);
        }
    }
};

private void downloadApk() {
    downLoadThread = new Thread(mdownApkRunnable);
    downLoadThread.start();
}

/** 以系統安裝器開啟 APK */
private void installApk() {
    File apkfile = new File(apkFilePath);
    if (!apkfile.exists()) {
        return;
    }
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
            "application/vnd.android.package-archive");
    mContext.startActivity(i);
}

主線程的 Handler 負責把四種狀態翻譯成使用者看得到的回饋:更新進度條、關閉下載框並安裝、提示檢查 SD 卡,或依錯誤碼區分「網路不給力」與「找不到資源」。整份程式流暢的關鍵就在這裡——所有耗時動作都在子線程,UI 只負責呈現。

要留意的是,這份寫法屬於較早期的.Net 風格 HTTP 連線(DefaultHttpClient 已在 Android 6.0 移除),Environment.getExternalStorageDirectory() 也需要 WRITE_EXTERNAL_STORAGE 與後續版本的分區儲存/Scoped Storage 配套處理,而 FileProvider 更是 Android 7.0 以後 file:// URI 分享的必要條件。若要在新專案沿用這套邏輯,建議把網路層換成 HttpURLConnection 或 OkHttp,並改用 FileProvider 授權安裝。

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