uni-app 打包后 app 内部在线 全局更新 版本

730 阅读1分钟

领导新需求,使用uni-app 如果在线更新app版本


虽然官方有例子,但是导入官方例子却不行。如何在app 内部更新。鼓捣了挺长时间,最后解决了问题。问题挺多我就一一列出来并附上代码。

1.完成思路

数据库存好版本号,在项目中main.js 中配置好版本号,但需要注意 新生成app 版本,要比正式版用户的高。

在这里插入图片描述

在这里插入图片描述

2.在app.vue 中查看是否版本有更新?如果有更新找到地址去下载,并且替换本地文件,然后调取原生安装app 即可。

出现的问题

1.下载路径 使用手机模拟的路径和真机的不一样。 注意 _downloads

var fileName = '_downloads/fileName_' + this.$app_version + '.apk';

2.下载后版本后低于用户使用版本,安装失败。 生成app 时创建的版本号低,导致无法安装。

代码附上


			//#ifdef APP-PLUS
			var server = this.$serverUrl + "/util/api"; //检查更新地址
			var req = { //升级检测数据
				"version": this.$app_version,
				't': new Date().getTime()
			};
			uni.request({
				url: server,
				data: req,
				success: (res) => {
					console.log(res.data);
					console.log("数据为" + this.$version);
					if (res.statusCode == 200 && res.data.result.status === 1) {
						var urls = res.data.result.url;
						var force = res.data.result.force;
						console.log(res.data.result)
						var fileName = '_downloads/文件名前缀_' + this.$app_version + '.apk';
						uni.showModal({ //提醒用户更新
							title: "更新提示",
							content: res.data.result.note,
							showCancel: force == 0 ? true : false,
							success: (res) => {
								if (res.confirm) { 
									var wgtWaiting = null;
									wgtWaiting = plus.nativeUI.showWaiting("开始下载");
									console.log(urls)
									var down=plus.downloader.createDownload(urls, {
										filename: fileName 
									}, function(download, status) {
										console.log('下载成功回调');
										uni.hideLoading();
										// console.log(JSON.stringify(download));
										if (status == 200) {
											console.log(fileName);
											installApk(down.filename); // 更新应用资源  
										}
									});
									down.start();
									down.addEventListener("statechanged", function(download, status) {
										switch (download.state) {
											case 2:
												wgtWaiting.setTitle("已连接到服务器");
												break;
											case 3:
												var percent = download.downloadedSize / download.totalSize * 100;
												wgtWaiting.setTitle("已下载 " + parseInt(percent) + "%");
												break;
											case 4:
												wgtWaiting.setTitle("下载完成");
												break;
										}
									});
									
								}
							}
						});

					}
				}
			})


			// 更新应用资源  
			var installApk = function(path) {
				plus.runtime.install(path, {}, function() {
					console.log("安装文件成功!");
					
					plus.runtime.restart();


				}, function(e) {
					uni.hideLoading();
					console.log(JSON.stringify(e)); //这里!e一直为null,path路径为_downloads/apk/10.apk  
					uni.showToast({
						title: '安装失败',
						mask: false,
						duration: 1500
					});
				});
			}
			//#endif