編輯:關於 Android 程式設計
幾乎所有 App 都有「發現新版本,請更新」的功能。本文將一步步實作這樣一套自動更新機制:檢測更新、提示使用者、下載 APK、並在完成后自動跳轉安裝。

這個類封裝了完整的更新流程,透過 Handler 接收下載進度並更新進度條:
public class UpdateManger {
private Context mContext;
private String updateMsg = "有最新的軟體包,請下載!";
private String apkUrl = "https://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk";
private Dialog noticeDialog; // 提示更新的對話框
private Dialog downloadDialog; // 下載對話框
private static final String savePath = "/sdcard/updatedemo/";
private static final String saveFileName = savePath + "UpdateDemoRelease.apk";
private ProgressBar mProgress;
private static final int DOWN_UPDATE = 1;
private static final int DOWN_OVER = 2;
private int progress; // 當前進度
private Thread downLoadThread; // 下載線程
private boolean interceptFlag = false; // 使用者取消下載
// 通知處理刷新界面的 handler
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWN_UPDATE:
mProgress.setProgress(progress);
break;
case DOWN_OVER:
installApk();
break;
}
super.handleMessage(msg);
}
};
public UpdateManger(Context context) {
this.mContext = context;
}
// 顯示更新程式對話框,供主程式呼叫
public void checkUpdateInfo() {
showNoticeDialog();
}
private void showNoticeDialog() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
builder.setTitle("軟體版本更新");
builder.setMessage(updateMsg);
builder.setPositiveButton("下載", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
showDownloadDialog();
}
});
builder.setNegativeButton("以後再說", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
noticeDialog = builder.create();
noticeDialog.show();
}
按下「下載」後會彈出含進度條的對話框,並在子線程中執行實際的檔案下載。下載過程中透過 Handler 不斷更新進度,完成後觸發安裝:
protected void showDownloadDialog() {
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
builder.setTitle("軟體版本更新");
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.progress);
builder.setView(v); // 將對話框內容設為一個 View
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
interceptFlag = true; // 使用者取消下載
}
});
downloadDialog = builder.create();
downloadDialog.show();
downloadApk();
}
private void downloadApk() {
downLoadThread = new Thread(mdownApkRunnable);
downLoadThread.start();
}
protected void installApk() {
File apkfile = new File(saveFileName);
if (!apkfile.exists()) {
return;
}
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
"application/vnd.android.package-archive");
mContext.startActivity(i);
}
private Runnable mdownApkRunnable = new Runnable() {
@Override
public void run() {
try {
URL url = new URL(apkUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream ins = conn.getInputStream();
File file = new File(savePath);
if (!file.exists()) {
file.mkdir();
}
File ApkFile = new File(saveFileName);
FileOutputStream outStream = new FileOutputStream(ApkFile);
int count = 0;
byte buf[] = new byte[1024];
do {
int numread = ins.read(buf);
count += numread;
progress = (int) (((float) count / length) * 100); // 計算下載進度
mHandler.sendEmptyMessage(DOWN_UPDATE);
if (numread <= 0) {
mHandler.sendEmptyMessage(DOWN_OVER); // 下載完成,通知安裝
break;
}
outStream.write(buf, 0, numread);
} while (!interceptFlag); // 點擊取消則停止下載
outStream.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ProgressBar
android:id="@+id/progress"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
在 onCreate() 中建立 UpdateManger 並呼叫檢測方法。此處要特別注意:必須傳入 Activity 本身,而非 getApplicationContext(),因為只有 Activity 才能彈出窗體:
mUpdateManger = new UpdateManger(MainActivity.this);
// 注意此處不能傳入 getApplicationContext(),會報錯,因為只有 Activity 才能添加窗體
mUpdateManger.checkUpdateInfo();
同時別忘了在清單檔中加入網路權限:
<uses-permission android:name="android.permission.INTERNET" />
—點擊下載—>
整套流程串起了對話框提示、子線程下載、進度更新與自動安裝,是一個非常實用的線上更新範本。
源碼剖析:為什麼谷歌要求用 newInstance 而不是構造函數來實例化 Fragment
翻 Google 官方文檔時會發現一種頗有意思的寫法——用靜態工廠方法來創建 Fragment。其實你在 Android Studio 裡新建一個 Blank Fragm
仿 iOS 效果:ScrollView 滑動時自動隱藏底部懸浮按鈕
做 Android App 常要複刻 iOS 的互動細節。這次的需求是:頁面上的 ScrollView 滑動時,浮在底部的功能按鈕要以動畫收起;滑動停止後,再動畫回到原位
Android Studio 使用 android-pdf-viewer 的問題與解法
需求背景 在 Android 中顯示 PDF,常見做法是先用 DownloadManager 下載檔案,再透過 PDFView 元件渲染。本文以 Android Stud
Android 性能優化:如何縮短應用啟動時間
一、先搞清楚啟動方式的差別 Android 中應用的啟動方式大致可分為兩類: 冷啟動:啟動應用時背景沒有該應用的行程,系統會重新 fork 一個新行程分配給它。 熱啟動