自動更新流程設計
- App 啟動/定時 → 請求版本資訊 API (JSON/XML)。
- 比對 `versionCode`,有新版 → 彈出更新對話框。
- 用戶確認 → 顯示進度對話框 → 背景執行緒下載 APK。
- 下載完成 → 呼叫系統安裝 Intent → 安裝完成 → 重啟 App。
- 支援取消下載、網路錯誤重試、MD5 校驗。
核心類:UpdateManager
public class UpdateManager {
private Context context;
private String apkUrl = "https://example.com/app-release.apk";
private String saveDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/MyApp/";
private String saveFileName = saveDir + "app-update.apk";
private Dialog noticeDialog, downloadDialog;
private ProgressBar progressBar;
private volatile boolean intercept = false;
private Thread downloadThread;
private static final int MSG_PROGRESS = 1, MSG_FINISH = 2;
private Handler handler = new Handler(Looper.getMainLooper()) {
@Override public void handleMessage(Message msg) {
if (msg.what == MSG_PROGRESS) progressBar.setProgress(progress);
else if (msg.what == MSG_FINISH) { downloadDialog.dismiss(); installApk(); }
}
};
public UpdateManager(Context ctx) { this.context = ctx; }
public void checkUpdate() {
// 這裡簡化:實際應請求後端 API 比對 versionCode
showNoticeDialog();
}
private void showNoticeDialog() {
new AlertDialog.Builder(context)
.setTitle("版本更新")
.setMessage("發現新版本 v2.0,包含功能優化與修復,是否立即更新?")
.setPositiveButton("立即更新", (d, w) -> { d.dismiss(); showDownloadDialog(); })
.setNegativeButton("稍後說", (d, w) -> d.dismiss())
.setCancelable(false)
.show();
}
private void showDownloadDialog() {
View view = LayoutInflater.from(context).inflate(R.layout.dialog_progress, null);
progressBar = view.findViewById(R.id.pb_download);
downloadDialog = new AlertDialog.Builder(context)
.setTitle("正在下載...")
.setView(view)
.setNegativeButton("取消", (d, w) -> { intercept = true; d.dismiss(); })
.setCancelable(false)
.create();
downloadDialog.show();
startDownload();
}
private void startDownload() {
intercept = false;
downloadThread = new Thread(() -> {
try {
URL url = new URL(apkUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
long total = conn.getContentLengthLong();
File dir = new File(saveDir);
if (!dir.exists()) dir.mkdirs();
File apkFile = new File(saveFileName);
try (InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(apkFile)) {
byte[] buffer = new byte[4096];
long downloaded = 0;
int len;
while (!intercept && (len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
downloaded += len;
progress = (int) (downloaded * 100 / total);
handler.sendEmptyMessage(MSG_PROGRESS);
}
if (!intercept) handler.sendEmptyMessage(MSG_FINISH);
}
} catch (Exception e) {
e.printStackTrace();
handler.post(() -> Toast.makeText(context, "下載失敗: " + e.getMessage(), Toast.LENGTH_SHORT).show());
}
});
downloadThread.start();
}
private void installApk() {
File file = new File(saveFileName);
if (!file.exists()) return;
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
// FileProvider 適配 Android 7.0+
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
uri = Uri.fromFile(file);
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intent);
}
}
必要配置
1. AndroidManifest 權限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" /> <!-- Android 8.0+ 安裝未知來源 -->
2. FileProvider (res/xml/file_paths.xml)
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="https://schemas.android.com/apk/res/android">
<files-path name="updates" path="." />
<external-files-path name="updates_ext" path="." />
<cache-path name="cache" path="." />
</paths>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
3. 版本檢查 API 設計建議
{
"versionCode": 200,
"versionName": "2.0.0",
"forceUpdate": false,
"downloadUrl": "https://cdn.example.com/app-2.0.0.apk",
"md5": "d41d8cd98f00b204e9800998ecf8427e",
"changelog": "1. 修復登入閃退\n2. 新增深色模式\n3. 優化啟動速度"
}
進階優化方向
- 斷點續傳:`RandomAccessFile` + `Range` Header。
- 增量更新:bsdiff/bspatch 生成 Patch 包,大幅減少流量。
- 靜默安裝:需系統簽名/Root/Device Owner 權限,普通 App 不可用。
- 應用內更新 (Play Core):Google Play In-App Update API,提供彈性/強制更新體驗。
- 架構升級:使用 OkHttp/Retrofit + Coroutines/Flow 替換 HttpURLConnection + Handler。