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

Android 版本檢測與自動升級功能完整實作

編輯:關於 Android 程式設計

我們大概都遇過這樣的體驗:開啟某個 App 時跳出提示,說有新版本可以下載。這個功能拆開來其實只有三個步驟:

  1. 取得本地的當前版本號;
  2. 向伺服器查詢最新版本並比對;
  3. 若有更新則下載 APK,下載完成後自動觸發安裝。

步驟一:取得本地版本號

/** 取得目前 App 的版本名稱 */
private String getVersionName() throws Exception {
    PackageManager packageManager = getPackageManager();
    // getPackageName() 取得目前應用程式的套件名,第二個參數 0 表示要版本資訊
    PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
    return packInfo.versionName;
}

步驟二:解析伺服器回傳的版本資訊

這裡假設伺服器回傳一份 XML,內含版本號、下載網址與更新說明。用 XmlPullParser 解析並封裝成實體物件:

public static UpdataInfo getUpdataInfo(InputStream is) throws Exception {
    XmlPullParser parser = Xml.newPullParser();
    parser.setInput(is, "utf-8");

    int type = parser.getEventType();
    UpdataInfo info = new UpdataInfo();

    while (type != XmlPullParser.END_DOCUMENT) {
        switch (type) {
            case XmlPullParser.START_TAG:
                if ("version".equals(parser.getName())) {
                    info.setVersion(parser.nextText());
                } else if ("url".equals(parser.getName())) {
                    info.setUrl(parser.nextText());
                } else if ("description".equals(parser.getName())) {
                    info.setDescription(parser.nextText());
                }
                break;
        }
        type = parser.next();
    }
    return info;
}

對應的實體類別:

public class UpdataInfo {
    private String version;
    private String url;
    private String description;

    public String getVersion() { return version; }
    public void setVersion(String version) { this.version = version; }

    public String getUrl() { return url; }
    public void setUrl(String url) { this.url = url; }

    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }
}

步驟三:下載 APK

public static File getFileFromServer(String path, ProgressDialog pd) throws Exception {
    // 先確認外部儲存空間已掛載且可寫
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return null;
    }
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(5000);

    pd.setMax(conn.getContentLength()); // 進度條上限 = 檔案大小
    InputStream is = conn.getInputStream();

    File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
    FileOutputStream fos = new FileOutputStream(file);
    BufferedInputStream bis = new BufferedInputStream(is);

    byte[] buffer = new byte[1024];
    int len, total = 0;
    while ((len = bis.read(buffer)) != -1) {
        fos.write(buffer, 0, len);
        total += len;
        pd.setProgress(total);
    }
    fos.close();
    bis.close();
    is.close();
    return file;
}

步驟四:比對版本並串起流程

把網路請求放到子執行緒,透過 Handler 回主執行緒處理 UI:

public class CheckVersionTask implements Runnable {
    public void run() {
        try {
            String path = getResources().getString(R.string.serverurl);
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            InputStream is = conn.getInputStream();

            info = UpdataInfoParser.getUpdataInfo(is);

            if (info.getVersion().equals(versionname)) {
                Message msg = new Message();
                msg.what = UPDATA_CLIENT_NONE;
                handler.sendMessage(msg);
            } else {
                Message msg = new Message();
                msg.what = UPDATA_CLIENT;
                handler.sendMessage(msg);
            }
        } catch (Exception e) {
            Message msg = new Message();
            msg.what = GET_UNDATAINFO_ERROR;
            handler.sendMessage(msg);
            e.printStackTrace();
        }
    }
}

Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case UPDATA_CLIENT:
                showUpdataDialog();
                break;
            case GET_UNDATAINFO_ERROR:
                Toast.makeText(getApplicationContext(), "獲取伺服器更新資訊失敗", 1).show();
                LoginMain();
                break;
            case DOWN_ERROR:
                Toast.makeText(getApplicationContext(), "下載新版本失敗", 1).show();
                LoginMain();
                break;
        }
    }
};

步驟五:提示更新與安裝

protected void showUpdataDialog() {
    AlertDialog.Builder builer = new Builder(this);
    builer.setTitle("版本升級");
    builer.setMessage(info.getDescription());

    builer.setPositiveButton("確定", new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            downLoadApk();
        }
    });
    builer.setNegativeButton("取消", new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            LoginMain();
        }
    });

    builer.create().show();
}

protected void downLoadApk() {
    final ProgressDialog pd = new ProgressDialog(this);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setMessage("正在下載更新");
    pd.show();

    new Thread() {
        @Override
        public void run() {
            try {
                File file = DownLoadManager.getFileFromServer(info.getUrl(), pd);
                sleep(3000);
                installApk(file);
                pd.dismiss();
            } catch (Exception e) {
                Message msg = new Message();
                msg.what = DOWN_ERROR;
                handler.sendMessage(msg);
                e.printStackTrace();
            }
        }
    }.start();
}

protected void installApk(File file) {
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file),
            "application/vnd.android.package-archive");
    startActivity(intent);
}

private void LoginMain() {
    startActivity(new Intent(this, MainActivity.class));
    finish();
}

這份程式碼的現代化建議

上面這套寫法是早期 Android 的標準做法,邏輯沒問題,但放到今天有幾個地方必須調整:

  • FileProvider:Android 7.0(API 24)之後,把 file:// Uri 直接傳給其他應用會觸發 FileUriExposedException。必須改用 FileProvider.getUriForFile() 產生 content:// Uri,並在 manifest 中宣告 provider 與 FLAG_GRANT_READ_URI_PERMISSION。
  • 安裝未知來源的應用:Android 8.0 起改為「個別權限」,需要動態申請 REQUEST_INSTALL_PACKAGES。
  • 下載位置:寫入 Environment.getExternalStorageDirectory() 已不建議,應改用 App 專用目錄 getExternalFilesDir() 或 getFilesDir(),可免去寫入權限申請。
  • 版本比較:字串直接 equals() 有陷阱,1.10 與 1.9 的字串比較結果會不如預期,應拆成數值逐段比較。
  • 網路請求:HttpURLConnection 搭配自建 Thread 的方式建議替換為 OkHttp 或 Retrofit,並用 ViewModel + Coroutine 取代 Handler。
  • 進度更新:在子執行緒直接操作 ProgressDialog 是不安全的,UI 更新必須回到主執行緒。

如果你只是要快速做出一個可用的升級流程,上面的程式碼足夠理解原理;但要在正式產品中使用,務必把這幾個平台差異補齊。

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