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

實作 Android App 自動更新:版本檢查、下載與安裝全流程

編輯:關於 Android 程式設計

我們日常使用的 App 幾乎都有自動更新功能,一鍵就能完成升級。得益於 Android 的套件管理與安裝機制,這個功能做起來其實相當直觀。以下逐步實作。

1. 前置知識:讀取版本資訊

每個 APK 的版本標識定義在 AndroidManifest.xml 中:

 <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.myapp" android:versionCode="1" android:versionName="1.0.0"> <application></application> </manifest> 

其中 versionCode 是整數,versionName 是字串。由於 versionName 主要給使用者看,不易比較大小,因此升級判斷應以 versionCode 為準。

讀取方式可透過 PackageManager:

 public static int getVerCode(Context context) { int verCode = -1; try { verCode = context.getPackageManager().getPackageInfo( "com.myapp", 0).versionCode; } catch (NameNotFoundException e) { Log.e(TAG, e.getMessage()); } return verCode; } public static String getVerName(Context context) { String verName = ""; try { verName = context.getPackageManager().getPackageInfo( "com.myapp", 0).versionName; } catch (NameNotFoundException e) { Log.e(TAG, e.getMessage()); } return verName; } 

另一種做法是把 versionName 抽成字串資源,寫成 android:versionName="@string/app_versionName",再於 values/strings.xml 中定義,之後就能直接取用:

 public static String getVerName(Context context) { String verName = context.getResources() .getText(R.string.app_versionName).toString(); return verName; } 

應用名稱同理:

 public static String getAppName(Context context) { String verName = context.getResources() .getText(R.string.app_name).toString(); return verName; } 

2. 整體流程

比較版本 → 下載 → 安裝。

3. 版本檢查

在伺服器放置最新 APK,例如 https://localhost/myapp/myapp.apk,同時提供一份版本資訊檔,例如 https://localhost/myapp/ver.json:

 [{"appname":"jtapp12","apkname":"jtapp-12-updateapksamples.apk","verName":1.0.1,"verCode":2}]

客戶端讀取並解析:

 private boolean getServerVer () { try { String verjson = NetworkTool.getContent(Config.UPDATE_SERVER + Config.UPDATE_VERJSON); JSONArray array = new JSONArray(verjson); if (array.length() > 0) { JSONObject obj = array.getJSONObject(0); try { newVerCode = Integer.parseInt(obj.getString("verCode")); newVerName = obj.getString("verName"); } catch (Exception e) { newVerCode = -1; newVerName = ""; return false; } } } catch (Exception e) { Log.e(TAG, e.getMessage()); return false; } return true; } 

接著比對兩端版本:

 if (getServerVerCode()) { int vercode = Config.getVerCode(this); // 用到前面第一節寫的方法 if (newVerCode > vercode) { doNewVersionUpdate(); // 更新新版本 } else { notNewVersionShow(); // 提示當前為最新版本 } } 

兩個分支的提示視窗:

 private void notNewVersionShow() { int verCode = Config.getVerCode(this); String verName = Config.getVerName(this); StringBuffer sb = new StringBuffer(); sb.append("當前版本:"); sb.append(verName); sb.append(" Code:"); sb.append(verCode); sb.append(",/n已是最新版,無需更新!"); Dialog dialog = new AlertDialog.Builder(Update.this).setTitle("軟件更新") .setMessage(sb.toString())// 設置內容 .setPositiveButton("確定",// 設置確定按鈕 new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }).create();// 創建 // 顯示對話框 dialog.show(); } private void doNewVersionUpdate() { int verCode = Config.getVerCode(this); String verName = Config.getVerName(this); StringBuffer sb = new StringBuffer(); sb.append("當前版本:"); sb.append(verName); sb.append(" Code:"); sb.append(verCode); sb.append(", 發現新版本:"); sb.append(newVerName); sb.append(" Code:"); sb.append(newVerCode); sb.append(", 是否更新?"); Dialog dialog = new AlertDialog.Builder(Update.this) .setTitle("軟件更新") .setMessage(sb.toString()) // 設置內容 .setPositiveButton("更新",// 設置確定按鈕 new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { pBar = new ProgressDialog(Update.this); pBar.setTitle("正在下載"); pBar.setMessage("請稍候..."); pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER); downFile(Config.UPDATE_SERVER + Config.UPDATE_APKNAME); } }) .setNegativeButton("暫不更新", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // 點擊"取消"按鈕之後退出程序 finish(); } }).create();// 創建 // 顯示對話框 dialog.show(); } 

4. 下載模組

 void downFile(final String url) { pBar.show(); new Thread() { public void run() { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); long length = entity.getContentLength(); InputStream is = entity.getContent(); FileOutputStream fileOutputStream = null; if (is != null) { File file = new File( Environment.getExternalStorageDirectory(), Config.UPDATE_SAVENAME); fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int ch = -1; int count = 0; while ((ch = is.read(buf)) != -1) { fileOutputStream.write(buf, 0, ch); count += ch; if (length > 0) { } } } fileOutputStream.flush(); if (fileOutputStream != null) { fileOutputStream.close(); } down(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }.start(); } 

下載完成後透過 Handler 切回主線程,關閉進度框並進入安裝:

 void down() { handler.post(new Runnable() { public void run() { pBar.cancel(); update(); } }); } 

5. 安裝

 void update() { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(new File(Environment .getExternalStorageDirectory(), Config.UPDATE_SAVENAME)), "application/vnd.android.package-archive"); startActivity(intent); } 

關鍵是 MIME 型別 application/vnd.android.package-archive,系統收到後會自動導向安裝流程。

若應用已上架市集,那類平台本身就內建了更新機制;但如果是自有通路或企業內部發布,自建一套會方便許多。實務上更好的做法是:在 launcher Activity 啟動時就開一條工作線程去比對伺服器版本,發現有新版才跳轉到更新頁,這樣使用者體驗會更順,不必等進到主畫面才跳出提示。

另外提醒兩點現實考量:新版 Android 對 FileProvider 與套件安裝權限有更嚴格的要求,直接以 Uri.fromFile 傳遞檔案路徑會失敗;下載也建議改用下載管理器或成熟網路庫,並加上進度、續傳與失敗重試。

延伸閱讀可參考本站《Android 開發入門與進階教程》《Android 通信方式總結》《Android 基本組件用法總結》《Android 視圖 View 技巧總結》《Android 布局 layout 技巧總結》與《Android 控件用法總結》等專題。

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