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

Android 如何實現 App 內建的版本自動更新

編輯:關於 Android 程式設計

效果預覽

為什麼需要自動更新

對 Android 使用者來說,應用市場多到滿天飛:小米、魅族、百度、360、應用寶等等。當我們要上線新版本時,先不談渠道打包的繁瑣,光是逐一上傳到各大市場的工作量就很可觀。

更麻煩的情況是:好不容易全部上傳完畢,卻發現一個會導致閃退的小 Bug。改動明明很小,難道還要把所有市場的版本再重傳一遍?實務上這類需求幾乎必然會出現,因此把自動更新做進 App 裡,是非常值得的投資。市面上相關的第三方 SDK 不少,但自己實作一遍能更清楚每個環節。

整体流程

流程並不複雜:

  1. 使用者開啟 App 時,送出一個檢查版本的網路請求(或由服務端推送透傳訊息);
  2. 比對本機版本與伺服器版本,若本機較舊,提示使用者下載更新;
  3. 下載過程中透過通知列顯示進度;
  4. 下載完成後,呼叫系統安裝程式完成安裝。

至於強制升級,技術上可行但體驗很差,建議只在重大不相容變更時才考慮,並盡量減少使用。

涉及的知識點

  • 下載:非同步 HTTP 檔案下載,並監聽下載進度(此處使用 OkHttp)。
  • 通知:Notification,用於呈現下載進度。
  • 安裝:Intent,用於喚起系統安裝程式。

核心實作:下載服務

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;

import com.fangku.commonlibrary.utils.StorageUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import okhttp3.Call;

/**
 * 自動下載更新 apk 的服務
 */
public class DownloadService extends Service {

    private String mDownloadUrl; // APK 的下載路徑
    private NotificationManager mNotificationManager;
    private Notification mNotification;

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager =
                (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            notifyMsg("溫馨提醒", "檔案下載失敗", 0);
            stopSelf();
        }
        mDownloadUrl = intent.getStringExtra("apkUrl");
        downloadFile(mDownloadUrl);
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void notifyMsg(String title, String content, int progress) {
        // 為了向下相容,採用 v7 包的 NotificationCompat
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.icon_login_logo)
               .setLargeIcon(BitmapFactory.decodeResource(
                       getResources(), R.mipmap.icon_login_logo))
               .setContentTitle(title);

        if (progress > 0 && progress < 100) {
            builder.setProgress(100, progress, false); // 下載進行中
        } else {
            builder.setProgress(0, 0, false);
        }

        builder.setAutoCancel(true);
        builder.setWhen(System.currentTimeMillis());
        builder.setContentText(content);

        if (progress >= 100) {
            builder.setContentIntent(getInstallIntent()); // 下載完成,可點擊安裝
        }

        mNotification = builder.build();
        mNotificationManager.notify(0, mNotification);
    }

    /** 建構點擊後安裝 apk 的 PendingIntent */
    private PendingIntent getInstallIntent() {
        File file = new File(StorageUtil.DOWNLOAD_DIR + "APP檔案名稱");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()),
                              "application/vnd.android.package-archive");
        return PendingIntent.getActivity(this, 0, intent,
                                         PendingIntent.FLAG_UPDATE_CURRENT);
    }

    /** 下載 apk 檔案 */
    private void downloadFile(String url) {
        OkHttpUtils.get().url(url).build()
            .execute(new FileCallBack(StorageUtil.DOWNLOAD_DIR, "APP檔案名稱") {
                @Override
                public void onError(Call call, Exception e, int id) {
                    notifyMsg("溫馨提醒", "檔案下載失敗", 0);
                    stopSelf();
                }

                @Override
                public void onResponse(File response, int id) {
                    notifyMsg("溫馨提醒", "檔案下載已完成", 100);
                    stopSelf();
                }

                @Override
                public void inProgress(float progress, long total, int id) {
                    // progress * 100 為目前下載進度
                    if ((int) (progress * 100) % 10 == 0) {
                        // 每下載 10% 更新一次,避免頻繁刷新
                        notifyMsg("溫馨提醒", "檔案正在下載..", (int) (progress * 100));
                    }
                }
            });
    }
}

觸發更新

在需要檢查更新的時機(例如設定頁的「版本檢查」)啟動這個服務即可:

Intent intent = new Intent(mContext, DownloadService.class);
intent.putExtra("apkUrl", "APK 下載網址");
startService(intent);

實務上的建議

上面的程式碼只示範了本機端的下載與安裝。在真實專案中,應該與服務端配合:

  1. App 啟動時比對版本號,若低於伺服器版本,由服務端推送含新版本下載網址的透傳訊息;
  2. 依該網址下載並安裝新版;
  3. 遇到不再相容舊版的重大更新時,才考慮強制升級。

另外有兩個實務細節值得注意:下載檔案要寫入 App 專屬或公共媒體目錄,並依目標 Android 版本處理儲存空間權限;在 Android 7.0 以上安裝 APK 需要 FileProvider,直接用 file:// URI 會拋出 FileUriExposedException,這是新舊專案最常踩到的差異。

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