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

Android 版本更新全流程:檢測、下載、安裝一次搞懂

編輯:關於 Android 程式設計

版本更新幾乎是每個專案都必備的功能。整體思路其實很單純:取得客戶端目前的版本號,向伺服器詢問是否有新版本;若有,就下載 APK 並觸發安裝。真正需要花心思的是細節——進度回饋、可取消、錯誤處理,以及不同 Android 版本的新限制。

入口:一行就啟動檢查

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UpdateManager um = new UpdateManager(MainActivity.this);
        um.checkUpdateInfo();
    }
}

版本比較:先問自己現在是幾版

private String getVersionName(Context context) {
    try {
        // 包名換成自己應用的即可
        return context.getPackageManager()
                .getPackageInfo("com.home.update", 1).versionName;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
        return "";
    }
}

拿本地版本號向伺服器詢問,伺服器比對後回傳 JSON。這裡的協定由後端決定,示例中的結構是 code 加上 value 物件,內含最新 version 與下載 url:

private boolean testVersion(String version) {
    String url = CHECKURL + "?version=" + version;
    String result = get(url);
    try {
        JSONObject jsonObj = new JSONObject(result);
        if (jsonObj.getInt("code") == 0) {
            JSONObject valueObj = jsonObj.getJSONObject("value");
            String lastVersion = valueObj.getString("version");
            downloadUrl = valueObj.getString("url");
            return !version.equals(lastVersion);   // 不同就代表要更新
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return false;
}

網路請求的部分用 HttpClient 發 GET,把回應逐行讀進 StringBuffer:

HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    reader = new BufferedReader(new InputStreamReader(
            response.getEntity().getContent()));
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
} else if (response.getStatusLine().getStatusCode()
        == HttpStatus.SC_SERVICE_UNAVAILABLE) {
    result = "維護或繁忙";
}

兩個對話框:先問,再顯示進度

需要更新時先彈出提示框,讓使用者決定:

AlertDialog.Builder builder = new Builder(context);
builder.setTitle("軟件版本更新");
builder.setMessage("版本可以更新哦");
builder.setPositiveButton("下載", (dialog, which) -> {
    dialog.dismiss();
    showDownloadDialog();
});
builder.setNegativeButton("以後再說", (dialog, which) -> dialog.dismiss());
noticeDialog = builder.create();
noticeDialog.show();

按下下載後,換成帶 ProgressBar 的進度框,並提供取消:

View v = LayoutInflater.from(context).inflate(R.layout.progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.progress);
builder.setView(v);
builder.setNegativeButton("取消", (dialog, which) -> {
    dialog.dismiss();
    interceptFlag = true;    // 用旗標讓下載迴圈停下來
});

下載:背景執行緒 + Handler 更新進度

private Runnable downApkRunnable = new Runnable() {
    @Override
    public void run() {
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            int length = conn.getContentLength();

            File dir = new File(savePath);
            if (!dir.exists()) dir.mkdir();

            InputStream is = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(saveFileName);

            int count = 0;
            byte buf[] = new byte[1024];
            do {
                int numread = is.read(buf);
                count += numread;
                progress = (int) (((float) count / length) * 100);
                handler.sendEmptyMessage(DOWN_UPDATE);   // 通知更新進度條

                if (numread <= 0) {
                    handler.sendEmptyMessage(DOWN_OVER); // 下載完成
                    break;
                }
                fos.write(buf, 0, numread);
            } while (!interceptFlag);   // 按下取消即停止

            fos.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};

Handler 收到 DOWN_OVER 後關掉進度框,直接觸發安裝:

private void installApk() {
    File apkfile = new File(saveFileName);
    if (!apkfile.exists()) return;

    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
            "application/vnd.android.package-archive");
    context.startActivity(i);
}

從 2.x 到現在:這段程式碼要改哪些地方

這份寫法有它的時代背景,直接搬到新專案會遇到幾個問題,值得逐項說明:

主執行緒禁止網路訪問(Android 4.0 起)。版本檢查的 testVersion() 若直接呼叫在主執行緒上,會拋 NetworkOnMainThreadException。必須整段搬到背景執行緒,再把結果 post 回主執行緒彈對話框。

file:// URI 會 crashes(Android 7.0 起)。直接對其他 App 傳 file:// 會引發 FileUriExposedException。正確做法是改用 FileProvider 取得 content:// URI,並在 manifest 中宣告 provider 與 file_paths.xml,同時給予 FLAG_GRANT_READ_URI_PERMISSION。

安裝未知來源應用需要授權(Android 8.0 起)。必須宣告 REQUEST_INSTALL_PACKAGES 權限,並在執行期引導使用者到設定頁為你的 App 開啟「允許安裝未知應用」。

下載存路徑。寫入外部儲存空間需要執行期授權;比較乾淨的做法是改用 getExternalFilesDir() 或 App 私有快取目錄,就不需要任何權限。

HTTP 明文傳輸(Android 9 起預設禁止)。若下載網址是 http,必須在 network_security_config.xml 明確允許,或直接把伺服器升到 https。

這些限制的共通邏輯是:Android 逐漸把「 App 能對使用者裝置做什麼」的權力收緊。更新流程本身沒變,但每一步都要更明確地取得授權。另外,若只是想在背景可靠地抓完一個檔案,DownloadManager 與 WorkManager 都比自己刻下載迴圈省事得多。

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