先说实现逻辑:我选择原生app-云打包,打包时设置好版本号,打包后上传到后台管理的app版本管理中;页面在App.vue中加载时storage设置当前的app版本号,首页加载出来时调用后台管理上传的最新的app版本的接口,与storage中获取的版本号作比较,如版本号不一样则提示有新版本,点击下载然后安装!
方法1实现:
1.APP.vue页面中:
//当小程序初始化完成时,会触发 onLaunch(全局只触发一次)
onLaunch: function() {
//获取你打包时设置的版本号,然后设置到storage里
plus.runtime.getProperty(plus.runtime.appid,(wgtinfo)=>{
uni.setStorage({
key: 'wgtinfoVersionCode',
data: wgtinfo.versionCode
})
})
},
(下面是manifest.json文件里设置的版本号,下面是我测试填的版本号!)
2、Home首页中调用:进入app后直接进入到首页,我是在首页做的判断。
//页面加载时调用查询版本的方法
onLoad() {
this.getSysVersion()
},
以下代码在Home页面中的methods中。
//获取版本列表
getSysVersion() {
const _this = this;
//获取缓存中,当前app的版本号
uni.getStorage({
key: 'wgtinfoVersionCode',
success: (res) => {
this.wgtinfoVersionCode = res.data;
API.queryAppList({
page: 1,
limit: 10
}).then(res => {
if (res.status) {
let appdata = res.data.records[0]
// 后端返回的app版本和当前app版本比较
if (Number(appdata.versionCode) != Number(this.wgtinfoVersionCode)) {
uni.showModal({
title: "发现新版本",
content: "确认下载更新",
success: (res) => {
if (res.confirm ==
true) { //当用户确定更新,执行更新,下面方法进行下载app
this.appdownLoad(appdata.url);
} else {
return false
}
}
})
}
}
})
.catch(err => {
console.log(err)
})
}
})
},
//执行下载app
appdownLoad(url) {
var that = this;
uni.showLoading({
title: '安装包下载中……'
})
const downloadTask = uni.downloadFile({
url: url, //服务器 app 的下载地址
success: (downloadResult) => {
uni.hideLoading();
console.log(downloadResult)
if (downloadResult.statusCode === 200) {
uni.showModal({
title: '',
content: '下载成功,是否允许安装新版本?',
confirmText: '确定',
success: function(res) {
if (res.confirm == true) {
plus.runtime.install( //安装
downloadResult.tempFilePath, {
force: true
},
function(res) {
utils.showToast('更新成功,重启中');
plus.runtime.restart();
}
);
}
}
});
}
}
});
},
下面是效果图:
(1)检测是否有新版本
(2)确认下载
(3)下载成功,安装新版本
以上就是自动更新操作!
页面内手动监测app更新时也是上面同样的写法,最好写在公用方法中达到复用效果!
后台管理系统中要有个app版本管理模块: 能够把打包生成的apk文件上传到线上的服务器,用来管理版本。
要注意要和mainifest.json中基础配置版本设置结合起来,每次打完新的包上传apk文件到服务上,这样在下次打开app后会自动检测到然后更新!
服务器apk文件生成二维码,扫码可下载!
推荐使用下方这个二维码生成网站,还是挺不错的
草料二维码生成器
生成后可通过浏览器和微信扫码进行下载!
文章转载于 https://blog.csdn.net/annans/article/details/122039891