虽然不需要阿里云或腾讯云的支持,但是需要自己有稳定的服务器。
主要实现自动更新检查更新,显示更新进度,是否强制更新。
app代码
function checkUpdate(){
utils.get(utils.UPDATE_URL).then((res,err)=>{
if(res){
if(res.version > utils.appver){
uni.showModal({
title: '升级提示',
content: '发现新版本,是否现在升级?\n更新时间:' + res.time + (res.content?'\n升级内容:' + res.content:''),
showCancel: !res.is_mandatory,
success(e) {
if(e.confirm){
setAppUpdate(res);
}
}
})
}
return;
}
});
}
function setAppUpdate(updateInfo){
console.log('updateInfo',updateInfo);
let waiting = plus.nativeUI.showWaiting({
title: '下载进度 - 0%'
});
let downloadTask = uni.downloadFile({
url: updateInfo.url,
success(e) {
console.log('下载文件:',e);
plus.runtime.install(e.tempFilePath,
{force: updateInfo.is_mandatory},
()=>{
console.log('安装成功');
if(updateInfo.is_mandatory){
plus.runtime.restart();
return;
}else{
uni.showModal({
title: '升级提示',
content: '安装成功是否重启?',
showCancel: !updateInfo.is_mandatory,
success: res => {
if (res.confirm) {
//更新完重启app
plus.runtime.restart();
}
}
});
}
},(e)=>{
uni.showModal({
title: '更新失败',
content: '错误码:' + e.code + '\n错误详情:' + e.message,
showCancel: false
})
});
},
fail(e) {
console.log(e);
uni.showModal({
title: '下载错误',
showCancel: false,
content: ''
})
},
complete() {
uni.hideLoading();
waiting.close();
}
});
downloadTask.onProgressUpdate(res=>{
console.log('下载进度:',res);
waiting.setTitle('下载进度 - '+res.progress+'%')
})
}
存放在服务器中的升级文件的json
{
"version": 1.230905,//新程序的版本号
"url": "https://xxx.xxx/update/xxx/wgt/apk",//你的下载文件地址
"time": "2023/09/05",//更新日期
"content": "更新播放源",//更新内容
"is_mandatory": false,//是否强制更新
"platform": "android"//适配系统
}
其中utils开头的是引用的公共文件
utils.UPDATE_URL:是检查升级的连接,我用的是json文件。
utils.get:是自己封装的get请求
utils.appver:是当前app的版本号,没有读取系统的版本号,这样的好处就是不用担心忘记修改manifest.json文件中的版本号。
如果想实现更多功能,可以根据需求修改升级服务器的json字段。