uniapp 自动更新无需阿里云、腾讯云

虽然不需要阿里云或腾讯云的支持,但是需要自己有稳定的服务器。

主要实现自动更新检查更新,显示更新进度,是否强制更新。

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字段。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值