一、核心代码
step1|✨ 获取app版本
onLaunch: function() {
plus.runtime.getProperty(plus.runtime.appid, (widgetInfo)=> {
getApp().globalData.version = widgetInfo.version;
});
}
step2|✨ 从接口获取版本,对比step1版本
async checkApp() {
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) {
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() {
if(this.downloadTask) {
uni.$u.toast('取消下载安装!')
this.downloadTask.abort()
this.downloadTask = null
}
uni.navigateBack()
}
二、思路描述
若是需要热更新,跳转更新页面uni.redirectTo({ url:'/pages/settingInfo/aboutUs/aboutUs?type=1})
onLoad(options) {
if(options.type == 1) {
this.$nextTick(()=> {
this.checkApp()
})
}
}
其他情况是:用户点击版本号,自动检测是否需要热更新(调用this.checkApp)