web app升級—帶進度條的App自動更新

  帶進度條的App自動更新,效果以下圖所示:css

    技術:vue、vant-ui、5+vue

  封裝獨立組件AppProgress.vue:android

<template>
  <div>
    <van-dialog
      v-model="showProgress"
      confirm-button-text="後臺下載"
      class="app-update"
      @confirm="confirmClick"
    >
      <img src="../../assets/imgs/progress-bar.png" />
      <van-progress :percentage="percentageVal" />
      <div class="msg">版本更新中,請稍後...</div>
    </van-dialog>
  </div>
</template>

<script>
// app下載進度組件
export default {
  props: {
    // 進度值
    percentageVal: {
      type: Number,
      default: 0
    },
    // 是否顯示彈窗
    showProgress: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {}
  },
  methods: {
    confirmClick() {
      this.$emit('confirm');
    }
  }
}
</script>

<style lang="scss" scoped>
img {
  width: 270px;
  height: 163px;
  position: fixed;
  top: -35px;
  z-index: 2200;
}
</style>
<style lang="scss">
.app-update.van-dialog {
  overflow: visible;
  width: 270px;
  border-radius: 12px;
  .van-progress {
    margin-top: 124px;
    z-index: 2300;
  }
  .msg {
    font-size: 16px;
    font-weight: 600;
    color: white;
    position: absolute;
    top: 50px;
    z-index: 2300;
    width: 100%;
    text-align: center;
  }
  .van-dialog__footer {
    border-radius: 12px;
    .van-button--default {
      .van-button__text {
        width: 105px;
        height: 26px;
        border-radius: 13px;
        background-color: #006eff;
        color: white;
        font-weight: 600;
        font-size: 12px;
        display: inline-block;
        margin-top: 10px;
        line-height: 26px;
      }
    }
  }
}
</style>

app升級代碼,封裝獨立js文件:appUpdateOptions.jsajax

/**
 * IOS 包發佈到應用市場後要更新此處的ID,替換掉測試ID:1053012308
 */
/* eslint-disable no-undef */
import { getVersion } from '@/services/login';
import request from '../../api/ajax.js';
import { Dialog } from 'vant';
import expiredStorage from '@/utils/expiredStorage.js';

function sleep(numberMillis) {
  var now = new Date();
  var exitTime = now.getTime() + numberMillis;
  while (true) {
    now = new Date();
    if (now.getTime() > exitTime) return;
  }
}

// Vue繼承的基礎對象
export default {
  data() {
    return {
      showProgress: false,
      percentageVal: 0
    };
  },
  methods: {
    appUpdate(ismanual) {
      const that = this;// 獲取5+運行環境的版本號
      plus.runtime.getProperty(plus.runtime.appid, function(inf) {
        const ver = inf.version;var ua = navigator.userAgent.toLowerCase();
        // 蘋果手機
        if (/iphone|ipad|ipod/.test(ua)) {
          // 獲取當前上架APPStore版本信息
          request
            .get('https://itunes.apple.com/lookup?id=1053012308', {
              id: 1053012308 // APP惟一標識ID
            })
            .then(data => {
              console.log('data:' + JSON.stringify(data));
              var resultCount = data.resultCount;
              for (var i = 0; i < resultCount; i++) {
                var normItem = data.results[i].version;if (normItem > ver) {
                  var _msg = '發現新版本:V' + normItem;
                  // plus.nativeUI.alert("發現新版本:V" + normItem);
                  Dialog.confirm({
                    title: '升級確認',
                    message: _msg
                  })
                    .then(() => {
                      // on confirm
                      // 執行升級操做
                      document.location.href =
                        'https://itunes.apple.com/cn/app/id1053012308?mt=8'; // 上新APPStore下載地址
                    })
                    .catch(() => {
                      // on cancel
                      expiredStorage.setItem('$upgradeTip', false, 1 / 12); // 1/12天內再也不顯示升級提示
                    });
                  return;
                }
              }
              if (ismanual) {
                plus.nativeUI.toast('當前版本號已經是最新');
              }
            });
        } else if (/android/.test(ua)) {
          getVersion().then(res => {if ((res.code = 200 && res.data.version > ver)) {
              var _msg = '發現新版本:V' + res.data.version;
              const apkUrl = res.data.redirectUrl;
              Dialog.confirm({
                title: '升級確認',
                message: _msg
              })
                .then(() => {
                  // on confirm
                  that.showProgress = true;
                  var dtask = plus.downloader.createDownload(
                    apkUrl,
                    {},
                    function(d, status) {
                      if (status == 200) {
                        // sleep(1000);
                        var path = d.filename; // 下載apk
                        plus.runtime.install(path); // 自動安裝apk文件
                        that.showProgress = false;
                      } else {
                        plus.nativeUI.alert('版本更新失敗:' + status);
                        that.showProgress = false;
                      }
                    }
                  );
                  try {
                    dtask.start(); // 開啓下載的任務
                    var prg = 0;
                    dtask.addEventListener('statechanged', function(
                      task,
                      status
                    ) {
                      // 給下載任務設置一個監聽 並根據狀態  作操做
                      switch (task.state) {
                        case 1:
                          //'正在下載';
                          break;
                        case 2:
                          // '已鏈接到服務器';
                          break;
                        case 3:
                          prg = parseInt(
                            (parseFloat(task.downloadedSize) /
                              parseFloat(task.totalSize)) *
                              100
                          );
                          that.percentageVal = prg;
                          break;
                        case 4:
                          that.showProgress = false;
                          break;
                      }
                    });
                  } catch (err) {
                    that.showProgress = false;
                    if (ismanual) {
                      plus.nativeUI.toast('網絡異常,請稍候再試' + err);
                    }
                  }
                })
                .catch(error => {
                  // on cancel
                  that.showProgress = false;
                  expiredStorage.setItem('$upgradeTip', false, 1 / 12); // 1/12天內再也不顯示升級提示
                });
            } else {if (ismanual) {
                plus.nativeUI.toast('當前版本號已經是最新');
              }
            }
          });
        }
      });
    },
    // 點擊肯定按鈕
    confirmClick() {
      this.showProgress = false;
    }
  }
};

 注意:這裏的版本號以字符串比較的方式可能會出現問題,正確的方式應該是:api

function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  var len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (var i = 0; i < len; i++) {
    var num1 = parseInt(v1[i])
    var num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }
  return 0
}

compareVersion('1.11.0', '1.9.9') // => 1 // 1表示 1.11.0比1.9.9要新
compareVersion('1.11.0', '1.11.0') // => 0 // 0表示1.11.0和1.11.0是同一個版本
compareVersion('1.11.0', '1.99.0') // => -1 // -1表示1.11.0比 1.99.0要老

調用代碼:服務器

import appUpdateOptions from '@/utils/mixins/appUpdateOptions.js'
import AppProgress from '@/components/common/AppProgress.vue';
export default {
  components: { AppProgress },
  props: {},
  mixins: [appUpdateOptions],
  methods: {
    // app更新
    appUpdateFuc() {
      const that = this;
      that.$mui.plusReady(function() {
        that.appUpdate(true);
      });
    },

結束.......網絡

相關文章
相關標籤/搜索