🍉uni-app自动更新并安装带显示进度

612 阅读1分钟

大家好,我是满心

前言

使用uniapp开发的项目,使用的uview1.0,需要在安卓端实现更新、安装,并带有进度条 介绍两种进度展示方式,各位自行选择: 1、plus.nativeUI方式
2、u-line-progress组件

判断客户端

uni.getSystemInfo({ //获取系统信息
	success: (res) => {
          if (res.platform == "android") {
          //此处业务逻辑省略
          }
	}
})

更新版本

说明:由于我这里和后台的逻辑是,首次请求后台时,后台将版本号下载url版本信息等 返给前端,前端将版本号进行缓存,然后下次检查版本时,将版本号传给后端,后端通过返回状态, 判断是否需要更新(方式比较low,毕竟后台就是这么写的,咱是前端只能按他的来😅)

使用u-line-progressplus.nativeUI方式

<u-modal v-model="showProcess" :show-cancel-button="true" :show-confirm-button="false" title="软件更新" @cancel="cancelDown" cancel-text="取消更新">
    <view class="u-update-content">
				<u-line-progress :percent="percent" :show-percent="true" :striped-active="true" :striped="true">
				</u-line-progress>
				<p class="tipSpan">软件更新中,请勿断开相框电源</p>
    </view>
</u-modal>

核心代码

此处去掉注释,就是第二种方式,默认使用进度条方式

this.dtask = plus.downloader.createDownload(this.downloadUrl, {}, function(d,status) { //新建下载任务
	if (status == 200) { //当下载完成
		plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, {}, function(error) { //安装应用
			uni.showToast({
			title: '安装失败',
			duration: 1500,
			icon: 'none'
			});
		})
	} else {
		uni.showToast({
		title: '更新失败',
		duration: 1500,
		icon: 'none'
		});
	}
})
	this.dtask.start();
	var prg = 0;
	// var showLoading = plus.nativeUI.showWaiting("正在下载");
	this.showProcess = true;
	let _this = this;
	this.dtask.addEventListener('statechanged', function(task, status) { //添加下载任务事件监听器
	// 给下载任务设置一个监听 并根据状态 做操作
	switch (task.state) {
		case 1:
        // showLoading.setTitle("正在下载");
			break;
		case 2:
		// showLoading.setTitle("已连接到服务器");
			break;
		case 3:
			prg = parseInt( //下载的进度
					(parseFloat(task.downloadedSize) / parseFloat(task.totalSize)) * 100
					);
					// showLoading.setTitle("版本更新,正在下载" + prg + "% ");
					_this.percent = prg;
					console.log(prg);
			break;
					case 4:
			// plus.nativeUI.closeWaiting(); //关闭系统提示框
			this.showProcess = false;
			//下载完成
			break;
			}
	});