uniapp App热更新

280 阅读1分钟

一、核心代码

step1|✨ 获取app版本

onLaunch: function() {// App应用生命周期
    // #ifdef APP-PLUS
    // 保存 app 版本信息
    plus.runtime.getProperty(plus.runtime.appid, (widgetInfo)=> {
        getApp().globalData.version = widgetInfo.version;
    });
    // #endif
}

step2|✨ 从接口获取版本,对比step1版本

// 检测是否热更新
async checkApp() {// 更新页面methods选项的方法
    if(this.isCheck) return 
    this.isCheck = true
    this.$refs.dyToast.loading('检查中...')
    try {
        let { data} = await SystemCenterApi.getVersionManage()
        let result = data.versionNum
        let newVersion = data.versionNum.split('.')
        let oldVersion = getApp().globalData.version.split('.')
        console.log('newVersion', newVersion);
        console.log('oldVersion', oldVersion);
        // 补丁更新
        if(newVersion[2]*1 > oldVersion[2]*1  || newVersion[1]*1 > oldVersion[1]*1) {
            this.download(data.versionUrl)
        }else {
            uni.$u.toast('当前版本是最新版本')
        }
    }catch(e) {
        throw e;
    }finally {
        this.isCheck = false
        this.$refs.dyToast.hide()
    }
},

step3|✨ app下载更新

// 下载补丁
download(wgtUrl) {// 更新页面methods选项的方法
    this.show = true // 展示更新弹框
    this.downloadTask = uni.downloadFile({
        url: wgtUrl,
        success: (downloadResult) => {
            console.log(downloadResult);
            if (downloadResult.statusCode === 200) {
                plus.runtime.install(downloadResult.tempFilePath, {force: true}, ()=> {
                    console.log('install success...');  
                    this.show = false;
                    plus.runtime.restart();  
                }, (e)=> {
                    this.show = false;
                    uni.$u.toast(e)
                    console.error('install fail...', e);  
                });  
            }
        },
        fail: (err) => {
            plus.nativeUI.toast("补丁下载失败")
            console.log(err);
        }
    })
    this.downloadTask.onProgressUpdate((res) => {
        this.percent = res.progress// 更新进度百分比
    });
},
// 关闭蒙层 中断下载
close() {// 更新页面methods选项的方法
    if(this.downloadTask) {
        uni.$u.toast('取消下载安装!')
        this.downloadTask.abort()
        this.downloadTask = null
    }
    uni.navigateBack()
}

二、思路描述

// 1. App的`onLaunch`应用生命周期调用接口,检测是否需要热更新
若是需要热更新,跳转更新页面uni.redirectTo({ url:'/pages/settingInfo/aboutUs/aboutUs?type=1})
// 2. ?type=1是一个标识,代表App启动后检测需要热更新
onLoad(options) {// 页面生命周期
    if(options.type == 1) {
        this.$nextTick(()=> {
            this.checkApp()
        })
    }
}
其他情况是:用户点击版本号,自动检测是否需要热更新(调用this.checkApp)