uniapp在线下载安装包更新app以及热更新

发布于:2024-08-22 ⋅ 阅读:(14) ⋅ 点赞:(0)

首先用getSystemInfo判断平台、 再通过json文件模拟接口 判断版本号是否一致 不一致则下载服务器apk进行更新
外加网络波动导致失败重新下载更新包

 uni.getSystemInfo({
      success: function (e) {
        // #ifndef H5
        // 获取手机系统版本
        const system = e.system.toLowerCase();
        const platform = e.platform.toLowerCase();
        // 判断是否为ios设备
        if (
          platform.indexOf("ios") != -1 &&
          (system.indexOf("ios") != -1 || system.indexOf("macos") != -1)
        ) {
          Vue.prototype.SystemPlatform = "apple";
        } else if (platform.indexOf("android") != -1 && system.indexOf("android") != -1) {
          Vue.prototype.SystemPlatform = "android";

          uni.request({
            url: "https://xxxxxxx.love/0.json", // JSON 文件地址
            success: (res) => {
              if (res.statusCode === 200) {
                const version = res.data.version; // 获取 版本字段
                if (version != "1.0.1") {
                  uni.showModal({
                    title: "更新提示",
                    content: "有新的版本可用,是否立即更新?",
                    success: (result) => {
                      if (result.confirm) {
                        const downloadTask = uni.downloadFile({
                          url: "https://xxxxxxx.love/lock.apk", // 更新包地址
                          success: (downloadResult) => {
                            if (downloadResult.statusCode === 200) {
                              const tempFilePath = downloadResult.tempFilePath;
                              // 保存文件到持久目录
                              uni.saveFile({
                                tempFilePath: tempFilePath,
                                success: (saveResult) => {
                                  console.log(
                                    "文件保存成功,路径:",
                                    saveResult.savedFilePath
                                  );
                                  uni.openDocument({
                                    filePath: saveResult.savedFilePath,
                                    success: function (res) {
                                      console.log(res, "打开安装包");
                                    },
                                  });
                                  return;
                                  // 提示用户去文件管理器中安装
                                  uni.showModal({
                                    title: "下载完成",
                                    content:
                                      "更新包下载完成,请在文件管理器中找到并安装更新包。",
                                    showCancel: false,
                                    success: () => {
                                      uni.hideLoading(); // 隐藏进度条
                                    },
                                  });
                                },
                                fail: (err) => {
                                  console.error("保存文件失败", err);
                                  uni.hideLoading(); // 隐藏进度条
                                },
                              });
                            }
                          },
                          fail: (err) => {
                            console.error("下载失败", err);
                            uni.hideLoading(); // 隐藏进度条
                          },
                        });

                        uni.showLoading({
                          title: "正在下载更新包",
                          mask: true,
                        });

                        let lastProgress = 0;
                        let lastUpdateTime = new Date().getTime();
                        const updateInterval = 1500;

                        downloadTask.onProgressUpdate((res) => {
                          const currentTime = new Date().getTime();
                          if (
                            res.progress - lastProgress >= 5 ||
                            currentTime - lastUpdateTime >= updateInterval
                          ) {
                            lastProgress = res.progress;
                            lastUpdateTime = currentTime;
                            uni.showLoading({
                              title: `下载中... ${res.progress}%`,
                              mask: true,
                            });
                          }
                        });
                      }
                    },
                  });
                }
              }
            },
            fail: (err) => {
              console.error("请求失败", err);
            },
          });
        } else {
          Vue.prototype.SystemPlatform = "devtools";
        }
        // #endif
      },
    });

在这里插入图片描述


新增
加入热更新

<script>
import Vue from "vue";
import store from "./store/index.js";
import updateCustomBarInfo from "./tuniao-ui/libs/function/updateCustomBarInfo.js";
export default {
  onLaunch() {
    this.checkSystemInfo();
    this.getCustomBarInfo();
    this.checkForAppUpdates();
    this.checkForHotUpdates();
  },

  methods: {
    /**
     * 检查系统信息以确定平台类型
     */
    checkSystemInfo() {
      uni.getSystemInfo({
        success: (e) => {
          const system = e.system.toLowerCase();
          const platform = e.platform.toLowerCase();

          if (
            platform.includes("ios") &&
            (system.includes("ios") || system.includes("macos"))
          ) {
            Vue.prototype.SystemPlatform = "apple";
          } else if (platform.includes("android") && system.includes("android")) {
            Vue.prototype.SystemPlatform = "android";
          } else {
            Vue.prototype.SystemPlatform = "devtools";
          }
        },
      });
    },

    /**
     * 获取并更新状态栏和自定义顶栏信息
     */
    getCustomBarInfo() {
      updateCustomBarInfo().then((res) => {
        store.commit("$tStore", {
          name: "vuex_status_bar_height",
          value: res.statusBarHeight,
        });
        store.commit("$tStore", {
          name: "vuex_custom_bar_height",
          value: res.customBarHeight,
        });
      });
    },

    /**
     * 检查并处理应用更新
     */
    checkForAppUpdates() {
      const that = this;
      uni.request({
        url: "https://kangkang.love/0.json",
        success: (res) => {
          if (res.statusCode === 200 && res.data.appVersion !== "1.0.1") {
            uni.showModal({
              title: "更新提示",
              content: `${res.data.appUpdateContent || ""}`,
              success: (result) => {
                if (result.confirm) {
                  that.downloadUpdatePackage();
                }
              },
            });
          }
        },
        fail: (err) => {
          console.error("请求失败", err);
        },
      });
    },

    /**
     * 下载并安装更新包
     */
    downloadUpdatePackage() {
      const downloadTask = uni.downloadFile({
        url: "http://cdn.kangkang.love/lock.apk",
        success: (downloadResult) => {
          if (downloadResult.statusCode === 200) {
            const tempFilePath = downloadResult.tempFilePath;
            uni.saveFile({
              tempFilePath,
              success: (saveResult) => {
                uni.openDocument({
                  filePath: saveResult.savedFilePath,
                  success: (res) => {
                    console.log(res, "打开安装包");
                  },
                });
              },
              fail: (err) => console.error("保存文件失败", err),
            });
          }
        },
        fail: (err) => console.error("下载失败", err),
      });

      uni.showLoading({
        title: "正在下载更新包",
        mask: true,
      });

      let lastProgress = 0;
      let lastUpdateTime = Date.now();
      const updateInterval = 1500;

      downloadTask.onProgressUpdate((res) => {
        const currentTime = Date.now();
        if (
          res.progress - lastProgress >= 5 ||
          currentTime - lastUpdateTime >= updateInterval
        ) {
          lastProgress = res.progress;
          lastUpdateTime = currentTime;
          uni.showLoading({
            title: `下载中... ${res.progress}%`,
            mask: true,
          });
        }
      });
    },

    /**
     * 检查并处理热更新
     */
    checkForHotUpdates() {
      const that = this;
      uni.request({
        url: "https://kangkang.love/0.json",
        success: (res) => {
          if (res.statusCode === 200 && res.data.hotUpdateVersion !== "1.0.0") {
            uni.showModal({
              title: "热更新提示",
              content: `${res.data.hotUpdateContent || ""}`,
              success: (result) => {
                if (result.confirm) {
                  that.downloadHotUpdatePackage();
                }
              },
            });
          }
        },
        fail: (err) => {
          console.error("热更新请求失败", err);
        },
      });
    },

    /**
     * 下载并处理热更新包
     */
    downloadHotUpdatePackage() {
      const that = this;
      const downloadTask = uni.downloadFile({
        url: "https://kangkang.love/update.wgt", // 热更新包地址
        success: (downloadResult) => {
          if (downloadResult.statusCode === 200) {
            const tempFilePath = downloadResult.tempFilePath;
            plus.runtime.install(
              tempFilePath,
              {
                force: true,
              },
              function (succ) {
                // console.log('install success...');
                plus.nativeUI.closeWaiting();
                plus.nativeUI.alert("更新完成!", function () {
                  // 热更新完成自动重启
                  plus.runtime.restart();
                });
              },
              function (e) {
                plus.nativeUI.closeWaiting();
                plus.nativeUI.alert("更新失败,点击确认手动更新", function () {
                  plus.runtime.openURL(_this.updateUrl);
                  plus.runtime.quit();
                });
                console.error("install fail...", e);
              }
            );
          }
        },
        fail: (err) => console.error("热更新包下载失败", err),
      });

      uni.showLoading({
        title: "正在下载热更新包",
        mask: true,
      });

      let lastProgress = 0;
      let lastUpdateTime = Date.now();
      const updateInterval = 1500;

      downloadTask.onProgressUpdate((res) => {
        const currentTime = Date.now();
        if (
          res.progress - lastProgress >= 5 ||
          currentTime - lastUpdateTime >= updateInterval
        ) {
          lastProgress = res.progress;
          lastUpdateTime = currentTime;
          uni.showLoading({
            title: `下载中... ${res.progress}%`,
            mask: true,
          });
        }
      });
    },
  },
};
</script>

<style lang="scss">
@import "./tuniao-ui/index.scss";
@import "./tuniao-ui/iconfont.css";
@import "./tuniao-ui/TnDouble.css";

page {
  background-color: rgb(235, 236, 240);
}
</style>