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

Android 版本檢測與自動更新完整實作

編輯:關於 Android 程式設計

對於已上線的 Android 應用而言,版本檢測與自動更新是一項不可或缺的功能。它能讓開發者迅速將新版功能與修補推送到使用者手中。本文將完整解析一個具備「檢測更新、下載安裝、清理暫存檔」三大功能的更新類別實作。

整體架構

這個 Update 類別主要負責三件事:透過網路位址檢測是否有新版本、下載並安裝更新檔、以及刪除下載過程中的暫時檔案。以下為完整的程式碼:

public class Update {

    // 呼叫更新的 Activity
    public Activity activity = null;
    // 當前版本號
    public int versionCode = 0;
    // 當前版本名稱
    public String versionName = "";
    // 控制台信息標識
    private static final String TAG = "AutoUpdate";
    // 文件當前路徑
    private String currentFilePath = "";
    // 安裝包文件臨時路徑
    private String currentTempFilePath = "";
    // 獲得文件擴展名字符串
    private String fileEx = "";
    // 獲得文件名字符串
    private String fileNa = "";
    // 服務器地址
    private String strURL = "https://127.0.0.1:8080/ApiDemos.apk";

    private ProgressDialog dialog;

    // 構造方法,獲得當前版本信息
    public Update(Activity activity) {
        this.activity = activity;
        getCurrentVersion();
    }

    // 檢測更新
    public void check() {
        // 檢測網絡
        if (isNetworkAvailable(this.activity) == false) {
            return;
        }
        // 如果網絡可用,檢測到新版本
        if (true) {
            // 彈出對話框,選擇是否需要更新版本
            showUpdateDialog();
        }
    }

    // 檢測是否有可用網絡
    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();
            return (info != null && info.isConnected());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 彈出對話框,選擇是否需要更新版本
    public void showUpdateDialog() {
        AlertDialog alert = new AlertDialog.Builder(this.activity)
            .setTitle("新版本").setIcon(R.drawable.ic_launcher)
            .setMessage("是否更新?")
            .setPositiveButton("是", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    downloadTheFile(strURL);
                    showWaitDialog();
                }
            })
            .setNegativeButton("否", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            }).show();
    }

    // 顯示更新狀態,進度條
    public void showWaitDialog() {
        dialog = new ProgressDialog(activity);
        dialog.setMessage("正在更新,請稍候...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.show();
    }

    // 獲得當前版本信息
    public void getCurrentVersion() {
        try {
            PackageInfo info = activity.getPackageManager().getPackageInfo(
                activity.getPackageName(), 0);
            this.versionCode = info.versionCode;
            this.versionName = info.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 截取文件名稱並執行下載
    private void downloadTheFile(final String strPath) {
        fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length()).toLowerCase();
        fileNa = strURL.substring(strURL.lastIndexOf("/") + 1, strURL.lastIndexOf("."));
        try {
            if (strPath.equals(currentFilePath)) {
                doDownloadTheFile(strPath);
            }
            currentFilePath = strPath;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        doDownloadTheFile(strPath);
                    } catch (Exception e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 執行新版本下載,並安裝
    private void doDownloadTheFile(String strPath) throws Exception {
        Log.i(TAG, "getDataSource()");
        if (!URLUtil.isNetworkUrl(strPath)) {
            Log.i(TAG, "服務器地址錯誤!");
        } else {
            URL myURL = new URL(strPath);
            URLConnection conn = myURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            if (is == null) {
                throw new RuntimeException("stream is null");
            }
            File myTempFile = File.createTempFile(fileNa, "." + fileEx);
            currentTempFilePath = myTempFile.getAbsolutePath();
            FileOutputStream fos = new FileOutputStream(myTempFile);
            byte buf[] = new byte[128];
            do {
                int numread = is.read(buf);
                if (numread <= 0) {
                    break;
                }
                fos.write(buf, 0, numread);
            } while (true);
            Log.i(TAG, "getDataSource() Download ok...");
            dialog.cancel();
            dialog.dismiss();
            openFile(myTempFile);
            try {
                is.close();
            } catch (Exception ex) {
                Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex);
            }
        }
    }

    // 打開文件進行安裝
    private void openFile(File f) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        String type = getMIMEType(f);
        intent.setDataAndType(Uri.fromFile(f), type);
        activity.startActivity(intent);
    }

    // 刪除臨時路徑裡的安裝包
    public void delFile() {
        Log.i(TAG, "The TempFile(" + currentTempFilePath + ") was deleted.");
        File myFile = new File(currentTempFilePath);
        if (myFile.exists()) {
            myFile.delete();
        }
    }

    // 獲得下載文件的類型
    private String getMIMEType(File f) {
        String type = "";
        String fName = f.getName();
        String end = fName.substring(fName.lastIndexOf(".") + 1, fName.length()).toLowerCase();
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
            || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
            type = "audio";
        } else if (end.equals("3gp") || end.equals("mp4")) {
            type = "video";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
            || end.equals("jpeg") || end.equals("bmp")) {
            type = "image";
        } else if (end.equals("apk")) {
            type = "application/vnd.android.package-archive";
        } else {
            type = "*";
        }
        if (end.equals("apk")) {
        } else {
            type += "/*";
        }
        return type;
    }
}

關鍵流程說明

整個更新流程可以拆解為以下幾個環節:

  1. 取得當前版本:透過 PackageManager 讀取應用程式的 versionCode 與 versionName,作為比對基礎。
  2. 網路檢測:呼叫 check() 時,會先透過 isNetworkAvailable() 確認網路是否可用,避免在離線狀態下進行無效操作。
  3. 下載更新檔:使用者在對話框按下「是」之後,會開啟一個新的執行緒進行下載,透過 URLConnection 串流讀取檔案並寫入暫存檔,避免阻塞 UI 執行緒。
  4. 觸發安裝:下載完成後,透過 getMIMEType() 判斷檔案類型(這裡為 APK,對應 application/vnd.android.package-archive),再以 ACTION_VIEW 意圖開啟安裝流程。
  5. 清理暫存檔:安裝完成後,可呼叫 delFile() 刪除暫時路徑中的安裝包,保持裝置空間整潔。

這套實作涵蓋了自動更新最核心的環節,開發時可根據實際需求調整伺服器位址與版本比對邏輯(範例中 check() 一律視為有新版本,實務上應替換為真正的版本比較判斷)。

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