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

Android 應用自檢更新完整實現(附源碼)

編輯:關於 Android 程式設計

應用上線後總會有修 bug、加功能的迭代需求,因此「檢查更新—提示—下載—安裝」這條鏈路幾乎是必備能力。本文給出一套可直接落地的實現,核心由三塊組成:版本比對、APK 下載、.xml 配置驅動。

整體流程

  1. 讀取本地 versionCode;
  2. 請求服務器上的 version.xml,解析出版本號、文件名的下載地址;
  3. 版本號更大則彈出提示框;
  4. 用戶確認後顯示帶進度條的下載框,在子線程中下載 APK 到外部存儲;
  5. 下載完成通過 Intent 觸發系統安裝器。

把版本信息放在服務器的 XML 裡而不是寫死在客戶端,意味著每次發新版只需要改服務器上的一個文件,不必重新打包發佈。

UpdateManager.java

package com.iteye.update;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class UpdateManager {

    /* 下載中 */
    private static final int DOWNLOAD = 1;
    /* 下載結束 */
    private static final int DOWNLOAD_FINISH = 2;

    /* 保存解析後的 XML 信息 */
    private HashMap<String, String> mHashMap;
    /* 下載保存路徑 */
    private String mSavePath;
    /* 記錄進度 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context mContext;
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD:
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    installApk();
                    break;
                default:
                    break;
            }
        }
    };

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    /** 檢測軟件更新 */
    public void checkUpdate() {
        if (isUpdate()) {
            showNoticeDialog();
        } else {
            Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
        }
    }

    /** 檢查是否有新版本 */
    private boolean isUpdate() {
        int versionCode = getVersionCode(mContext);
        ParseXmlService service = new ParseXmlService();
        try {
            String path = "https://your.server.com/xml/version.xml";
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(5 * 1000);
            conn.setRequestMethod("GET");
            InputStream inStream = conn.getInputStream();
            mHashMap = service.parseXml(inStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != mHashMap) {
            int serviceCode = Integer.valueOf(mHashMap.get("version"));
            if (serviceCode > versionCode) {
                return true;
            }
        }
        return false;
    }

    /** 獲取當前軟件版本號,對應 AndroidManifest.xml 中的 android:versionCode */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            versionCode = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /** 顯示更新提示框 */
    private void showNoticeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(R.string.soft_update_info);
        builder.setPositiveButton(R.string.soft_update_updatebtn,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        showDownloadDialog();
                    }
                });
        builder.setNegativeButton(R.string.soft_update_later,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }

    /** 顯示帶進度條的下載框 */
    private void showDownloadDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle(R.string.soft_updating);

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);

        builder.setNegativeButton(R.string.soft_update_cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        cancelUpdate = true;
                    }
                });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        downloadApk();
    }

    private void downloadApk() {
        new downloadApkThread().start();
    }

    /** 下載線程 */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";

                    URL url = new URL(mHashMap.get("url"));
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, mHashMap.get("name"));
                    FileOutputStream fos = new FileOutputStream(apkFile);

                    int count = 0;
                    byte buf[] = new byte[1024];
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);

                    fos.close();
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            mDownloadDialog.dismiss();
        }
    }

    /** 通過 Intent 觸發安裝 */
    private void installApk() {
        File apkfile = new File(mSavePath, mHashMap.get("name"));
        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);
    }
}

ParseXmlService.java

XML 文件很小,用 DOM 解析足夠直觀:

package com.iteye.update;

import java.io.InputStream;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ParseXmlService {

    public HashMap<String, String> parseXml(InputStream inStream) throws Exception {
        HashMap<String, String> hashMap = new HashMap<String, String>();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(inStream);

        Element root = document.getDocumentElement();
        NodeList childNodes = root.getChildNodes();

        for (int j = 0; j < childNodes.getLength(); j++) {
            Node childNode = (Node) childNodes.item(j);
            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            Element childElement = (Element) childNode;
            String name = childElement.getNodeName();
            String value = childElement.getFirstChild().getNodeValue();
            if ("version".equals(name) || "name".equals(name) || "url".equals(name)) {
                hashMap.put(name, value);
            }
        }
        return hashMap;
    }
}

服務器端配置 version.xml

<?xml version="1.0" encoding="UTF-8"?>
<update>
    <version>2</version>
    <name>app_v2.0.0.apk</name>
    <url>https://your.server.com/apk/app_v2.0.0.apk</url>
</update>

調用方式

UpdateManager manager = new UpdateManager(MainActivity.this);
manager.checkUpdate();

幾點實務提醒

這套代碼結構清晰、易於移植,但直接搬到今天的生產環境還需要補上幾塊:

  • 網絡請求必須異步。示例中 isUpdate() 在主線程發網絡請求,在新版本 Android 上會直接拋 NetworkOnMainThreadException,應遷移到 AsyncTask、線程池或 Kotlin 協程中執行。
  • 存儲位置與 FileProvider。Android 7.0 起 file:// URI 會觸發 FileUriExposedException,需改用 FileProvider 並授予臨時讀取權限。
  • 安裝未知來源應用。Android 8.0 後需要 REQUEST_INSTALL_PACKAGES 權限並引導用戶授予「安裝未知應用」。
  • 下載完整性校驗。建議在 version.xml 中增加文件大小或 MD5 字段,安裝前比對,避免半包或內容被替換。
  • 取消邏輯。cancelUpdate 只是讓循環退出,已寫入的殘包建議清理掉。

如果只是想盡快上線,如今更省事的做法是接入 Google Play 或廠商商店的應用內更新 API,把下載、校驗、安裝這些容易出兼容問題的細節交給系統組件。

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