Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 版本更新實戰:通知欄下載、進度同步與自動安裝

編輯:關於 Android 開發

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 是項目中自封裝的文件工具類,負責創建下載目錄與文件。

三、通知欄布局 view_notify_item.xml

<?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 換新即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved