編輯:關於 Android 開發
App 自更新幾乎是每個產品的標配。本文實現一套完整流程:檢查版本號 → 通知欄展示下載進度 → 下載完成自動跳轉安裝。

版本判斷依賴 AndroidManifest.xml 中的 versionCode。服務端放置新版本 apk,只要它的 versionCode 大於本地值,就說明有更新。取本地版本號的標準寫法:
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
int localVersion = packageInfo.versionCode;
拿這個值與服務端返回的版本號比較,本地較小則進入下載流程。
/**
* 下載 apk
*
* @param apkUri 下載地址
* @param version 版本標識,用來拼接文件名
*/
private void downLoadNewApk(String apkUri, String version) {
manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
notify = new Notification();
notify.icon = R.drawable.ic_launcher;
// 自定義通知欄布局
notify.contentView = new RemoteViews(context.getPackageName(), R.layout.view_notify_item);
manager.notify(100, notify);
File fileInstall = FileOperate.mkdirSdcardFile("downLoad", APK_NAME + version + ".apk");
downLoadSchedule(apkUri, completeHandler, context, fileInstall);
}
FileOperate 是項目中自封裝的文件工具類,負責創建下載目錄與文件。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:background="#00000000"
android:padding="5dp">
<ImageView
android:id="@+id/notify_icon_iv"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/notify_updata_values_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="6dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@id/notify_icon_iv"
android:gravity="center_vertical"
android:text="0%"
android:textColor="@color/white"
android:textSize="12sp" />
<ProgressBar
android:id="@+id/notify_updata_progress"
... />
</RelativeLayout>
/**
* 連接網絡下載文件,並把進度通過 Handler 回傳
*/
public static void downLoadSchedule(final String uri, final Handler handler,
Context context, final File file) {
if (!file.exists()) {
handler.sendEmptyMessage(-1);
return;
}
final int perLength = 4096;
new Thread() {
@Override
public void run() {
super.run();
try {
URL url = new URL(uri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream in = conn.getInputStream();
long length = conn.getContentLength();
byte[] buffer = new byte[perLength];
int len = -1;
FileOutputStream out = new FileOutputStream(file);
int temp = 0;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
int schedule = (int) ((file.length() * 100) / length);
// 只在整除的節點更新,避免每個循環都刷 UI
if (temp != schedule
&& (schedule % 10 == 0 || schedule % 4 == 0 || schedule % 7 == 0)) {
temp = schedule;
handler.sendEmptyMessage(schedule);
}
}
out.flush();
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
這裡有個實戰細節值得留意:進度回報做了節流。如果每次讀取都發一次消息,Handler 會被大量 UI 刷新任務塞滿,反而拖慢下載。只在百分比取模命中時才通知,是個簡單有效的折中。
/** 更新通知欄 */
private Handler completeHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what < 100) {
notify.contentView.setTextViewText(
R.id.notify_updata_values_tv, msg.what + "%");
notify.contentView.setProgressBar(
R.id.notify_updata_progress, 100, msg.what, false);
manager.notify(100, notify);
} else {
notify.contentView.setTextViewText(
R.id.notify_updata_values_tv, "下載完成");
notify.contentView.setProgressBar(
R.id.notify_updata_progress, 100, msg.what, false);
manager.cancel(100);
installApk(fileInstall);
}
}
};
/**
* 安裝 apk
*/
private void installApk(File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
context.startActivity(intent);
}
關鍵在於 MIME 類型必须是 application/vnd.android.package-archive,系統才會用安裝器接管這個 Intent。加上 FLAG_ACTIVITY_NEW_TASK 是因為此時可能處於非 Activity 上下文(例如 Service 中觸發)。
最後提醒一點:Android 8.0 之後,直接下載並安裝 apk 需要額外申請「安裝未知應用」權限(REQUEST_INSTALL_PACKAGES),同時 FileProvider 也取代了 Uri.fromFile,這套老寫法在新系統上需要相應改造。思路不變,API 換新即可。
Android 安全專項:AndBug 動態調試工具環境搭建與上手
Android 安全專項:AndBug 動態調試工具環境搭建與上手 AndBug 是一款面向 Android 的動態分析框架,能在不改動 apk 的前提下向目標進程注入腳
Android 主題 Theme 與樣式 Style 完全解析
每家公司出品的 App 都有統一的視覺風格,這背後離不開 theme 與 style。它們不僅能統一外觀,還能實現 Activity 切換動畫等效果,既簡潔又能大幅減少重
Android 開發:在 C 程式碼中呼叫 logcat 輸出日誌
Android 開發:在 C 程式碼中呼叫 logcat 輸出日誌 本文為〈Android Java 傳遞 int 型別陣列給 C〉加上「在 C 程式碼中呼叫 logca
Android 搜尋功能實作:SQLite 保存搜尋歷史與即時篩選
搜尋框不只是輸入框 在許多 App 中,搜尋功能不只是把關鍵字送出,還需要記住使用者最近搜尋過的內容。適當的歷史紀錄能減少重複輸入,也能讓使用者快速回到感興趣的主題。本文