編輯:關於 Android 程式設計
我們日常使用的 App 幾乎都有自動更新功能,一鍵就能完成升級。得益於 Android 的套件管理與安裝機制,這個功能做起來其實相當直觀。以下逐步實作。
每個 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; }
比較版本 → 下載 → 安裝。
在伺服器放置最新 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(); }
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(); } }); }
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 控件用法總結》等專題。
Android 觸控事件分發機制全解析:從 Activity 到 View 的完整路徑
上一篇文章我們談過觸控事件的「來源」——手指按下螢幕之後,原始輸入事件如何被系統封裝成 MotionEvent 並投遞到應用程序的視窗。這一篇接著往下走:當事件抵達 Ac
自定義 HorizontalScrollView 實作 QQ 側滑選單
QQ 風格側滑選單是常見的 Android 互動模式。要實作這類效果,可以自定義 HorizontalScrollView,讓選單在初始狀態下隱藏,並在使用者滑動時依手勢
仿 QQ5.0 側滑菜單:基於 ViewDragHelper 實現
QQ5.0 的側滑效果有多種實現方式,今天我們用 ViewDragHelper 來打造一個帶炫酷動畫的 SlidingMenu。 一、自定義 SlidingMenu 骨
小米手機通話自動錄音怎麼開?MIUI 設定圖解
小米手機自帶通話錄音功能,但預設情況下得在通話中手動點擊錄音才會開始錄。講事情講到一半才想起來按錄音,前面那段就補不回來了。MIUI 其實提供了自動錄音設定,可以省下這個