首先分析需求

  1. 我们要想实现这个自动更新的功能大致分三步:

1.查询线上版本号,然后拿本地版本号与之对比。
2. 若线上版本号比本地版本号大,则下载线上版本。
3. 把下载好版本安装,并替换当前旧版本。

代码实现

判断用户手机系统

  1. let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  2. let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);

如果是安卓系统的话,获取线上版本号和本地版本号对比

  1. this.$axios.get('/get/getAppVersion', {
  2. }).then((res) => {
  3. const { message, data, status } = res
  4. if (status == 200 && data.code == 200) {
  5. const { version, url ,text} = data.data
  6. this.wgtUrl = url
  7. console.log("地址", this.wgtUrl)
  8. if (this.banben == version) {
  9. this.isUptoDate = true //线上版本与本地版本相同
  10. } else { //有更新版本
  11. this.isUptoDate = false
  12. this.banben = version
  13. this.text=text
  14. plus.nativeUI.confirm("确定下载更新?", function (e) {
  15. if (e.index == 0) {
  16. that.downLoad(); // 执行下载函数
  17. } else { }
  18. }, "检测到最新版本", ["下载", "取消"]);
  19. }
  20. }
  21. })

下载函数

  1. downLoad() {
  2. let that = this
  3. const wgtUrl = this.wgtUrl
  4. plus.nativeUI.showWaiting("下载更新");
  5. plus.downloader.createDownload(wgtUrl, { filename: "_doc/update/" }, function (d, status) {
  6. if (status == 200) {
  7. console.log("下载更新成功:" + d.filename);
  8. that.installWgt(d.filename); // 安装wgt资源包
  9. } else {
  10. console.log("下载更新失败!");
  11. plus.nativeUI.toast("下载更新失败!");
  12. }
  13. plus.nativeUI.closeWaiting();
  14. }).start();
  15. },

安装函数

  1. installWgt(path) {
  2. plus.nativeUI.showWaiting("安装更新");
  3. plus.runtime.install(path, {}, function () {
  4. plus.nativeUI.closeWaiting();
  5. console.log("安装更新成功!");
  6. plus.nativeUI.alert("更新完成!", function () {
  7. plus.runtime.restart(); //安装成功后重启应用
  8. });
  9. }, function (e) {
  10. plus.nativeUI.closeWaiting();
  11. console.log("安装更新失败![" + e.code + "]:" + e.message);
  12. plus.nativeUI.toast("安装更新失败!");
  13. });
  14. }