編輯:關於 Android 程式設計
對於已上線的 Android 應用而言,版本檢測與自動更新是一項不可或缺的功能。它能讓開發者迅速將新版功能與修補推送到使用者手中。本文將完整解析一個具備「檢測更新、下載安裝、清理暫存檔」三大功能的更新類別實作。
這個 Update 類別主要負責三件事:透過網路位址檢測是否有新版本、下載並安裝更新檔、以及刪除下載過程中的暫時檔案。以下為完整的程式碼:
public class Update {
// 呼叫更新的 Activity
public Activity activity = null;
// 當前版本號
public int versionCode = 0;
// 當前版本名稱
public String versionName = "";
// 控制台信息標識
private static final String TAG = "AutoUpdate";
// 文件當前路徑
private String currentFilePath = "";
// 安裝包文件臨時路徑
private String currentTempFilePath = "";
// 獲得文件擴展名字符串
private String fileEx = "";
// 獲得文件名字符串
private String fileNa = "";
// 服務器地址
private String strURL = "https://127.0.0.1:8080/ApiDemos.apk";
private ProgressDialog dialog;
// 構造方法,獲得當前版本信息
public Update(Activity activity) {
this.activity = activity;
getCurrentVersion();
}
// 檢測更新
public void check() {
// 檢測網絡
if (isNetworkAvailable(this.activity) == false) {
return;
}
// 如果網絡可用,檢測到新版本
if (true) {
// 彈出對話框,選擇是否需要更新版本
showUpdateDialog();
}
}
// 檢測是否有可用網絡
public static boolean isNetworkAvailable(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null && info.isConnected());
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
// 彈出對話框,選擇是否需要更新版本
public void showUpdateDialog() {
AlertDialog alert = new AlertDialog.Builder(this.activity)
.setTitle("新版本").setIcon(R.drawable.ic_launcher)
.setMessage("是否更新?")
.setPositiveButton("是", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
downloadTheFile(strURL);
showWaitDialog();
}
})
.setNegativeButton("否", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
// 顯示更新狀態,進度條
public void showWaitDialog() {
dialog = new ProgressDialog(activity);
dialog.setMessage("正在更新,請稍候...");
dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
}
// 獲得當前版本信息
public void getCurrentVersion() {
try {
PackageInfo info = activity.getPackageManager().getPackageInfo(
activity.getPackageName(), 0);
this.versionCode = info.versionCode;
this.versionName = info.versionName;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
// 截取文件名稱並執行下載
private void downloadTheFile(final String strPath) {
fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length()).toLowerCase();
fileNa = strURL.substring(strURL.lastIndexOf("/") + 1, strURL.lastIndexOf("."));
try {
if (strPath.equals(currentFilePath)) {
doDownloadTheFile(strPath);
}
currentFilePath = strPath;
new Thread(new Runnable() {
@Override
public void run() {
try {
doDownloadTheFile(strPath);
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
// 執行新版本下載,並安裝
private void doDownloadTheFile(String strPath) throws Exception {
Log.i(TAG, "getDataSource()");
if (!URLUtil.isNetworkUrl(strPath)) {
Log.i(TAG, "服務器地址錯誤!");
} else {
URL myURL = new URL(strPath);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
if (is == null) {
throw new RuntimeException("stream is null");
}
File myTempFile = File.createTempFile(fileNa, "." + fileEx);
currentTempFilePath = myTempFile.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(myTempFile);
byte buf[] = new byte[128];
do {
int numread = is.read(buf);
if (numread <= 0) {
break;
}
fos.write(buf, 0, numread);
} while (true);
Log.i(TAG, "getDataSource() Download ok...");
dialog.cancel();
dialog.dismiss();
openFile(myTempFile);
try {
is.close();
} catch (Exception ex) {
Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex);
}
}
}
// 打開文件進行安裝
private void openFile(File f) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
String type = getMIMEType(f);
intent.setDataAndType(Uri.fromFile(f), type);
activity.startActivity(intent);
}
// 刪除臨時路徑裡的安裝包
public void delFile() {
Log.i(TAG, "The TempFile(" + currentTempFilePath + ") was deleted.");
File myFile = new File(currentTempFilePath);
if (myFile.exists()) {
myFile.delete();
}
}
// 獲得下載文件的類型
private String getMIMEType(File f) {
String type = "";
String fName = f.getName();
String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
|| end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
type = "audio";
} else if (end.equals("3gp") || end.equals("mp4")) {
type = "video";
} else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
|| end.equals("jpeg") || end.equals("bmp")) {
type = "image";
} else if (end.equals("apk")) {
type = "application/vnd.android.package-archive";
} else {
type = "*";
}
if (end.equals("apk")) {
} else {
type += "/*";
}
return type;
}
}
整個更新流程可以拆解為以下幾個環節:
PackageManager 讀取應用程式的 versionCode 與 versionName,作為比對基礎。check() 時,會先透過 isNetworkAvailable() 確認網路是否可用,避免在離線狀態下進行無效操作。URLConnection 串流讀取檔案並寫入暫存檔,避免阻塞 UI 執行緒。getMIMEType() 判斷檔案類型(這裡為 APK,對應 application/vnd.android.package-archive),再以 ACTION_VIEW 意圖開啟安裝流程。delFile() 刪除暫時路徑中的安裝包,保持裝置空間整潔。這套實作涵蓋了自動更新最核心的環節,開發時可根據實際需求調整伺服器位址與版本比對邏輯(範例中 check() 一律視為有新版本,實務上應替換為真正的版本比較判斷)。
Android 性能優化:常見內存洩漏的原因與應對
前言 內存洩漏,相信大家在開發中多少都遇到過。只不過它並不那麼顯而易見,因為它發生在堆中。要想檢測程序是否存在內存洩漏,通常可以借助 LeakCanary、MAT 等工具
用全域中斷點快速接入 Reveal
Reveal 是 iOS 開發中常用的介面除錯工具,能幫助開發者檢視畫面層級、屬性與視圖結構。若每個專案都手動加入 Reveal 的 framework,會相當麻煩。透過
NetworkOnMainThreadException 的成因與兩種解決方案
把 Android 4.0 之前的老項目搬到新版本上運行,網絡請求經常直接拋出 NetworkOnMainThreadException。這個異常並不是 bug,而是系統
Socket 實戰:Android 手機客戶端與 PC 服務端的區域網路聯調
本文示範如何把 Android 客戶端與 PC 上的 Java 服務端放在同一個區域網路內完成聯機測試。測試環境包含三個角色:PC 服務器、Android 平板客戶端、以