前言:
本文章使用的是vue+h5+plus技术,结合hbuildx打包的App,实现在App中检测版本更新功能。
下面贴码介绍:
getVersion()
{
zmitiUtil.Ajax('user/getVersion').then((res)=>{
console.log(res.data.version)
this.url=res.data.version.url
this.versionApp=res.data.version.version
if(version.version!=res.data.version.version)
{
this.showVersion=true
}
else{
this.showVersion=false
}
})
}
getVersion()
这个方法在页面加载完成后调用,主要用来检测当前App的版本和最新版本,如果当前版本和最新版本不同则给用户显示更新页面。
downLoad()
{
let that = this
that.showVersion=false
that.showProgress=true
const wgtUrl = that.url
// plus.nativeUI.showWaiting("新版本更新中,请耐心等待~");
var dtask = plus.downloader.createDownload("http://下载链接.apk", {}, function (d, status) {
if(status == 200) {
console.log("下载更新成功:" + d.filename);
that.installWgt(d.filename); // 安装wgt资源包
}
else
{
console.log("下载更新失败!");
plus.nativeUI.toast("下载更新失败!");
}
plus.nativeUI.closeWaiting();
})
dtask.start();
// 下载时实时显示下载进度
var prg = 0;
dtask.addEventListener('statechanged', function(task,status) {
// 给下载任务设置一个监听 并根据状态 做操作
switch (task.state) {
case 1:
//'正在下载';
break;
case 2:
// '已连接到服务器';
break;
case 3:
prg = parseInt(
(parseFloat(task.downloadedSize) /
parseFloat(task.totalSize)) *
100
);
that.percentageNum = prg; // 赋值给进度条组件
break;
case 4:
that.showProgress = false; // 进度隐藏
break;
}
});
}
downLoad()
这个方法是在用户点击更新时调用,主要实现了下载安装包以及实时更新进度条
installWgt(path) {
plus.nativeUI.showWaiting("安装更新");
plus.runtime.install(path, {}, function () {
plus.nativeUI.closeWaiting();
console.log("安装更新成功!");
plus.nativeUI.alert("更新完成!", function () {
plus.runtime.restart(); //安装成功后重启应用
});
}, function (e) {
plus.nativeUI.closeWaiting();
console.log("安装更新失败![" + e.code + "]:" + e.message);
plus.nativeUI.toast("安装更新失败!");
});
}
installWgt()
这个方法在一切准备就绪后安装App
总结:
在App中检测版本更新首先判断版本号是否是最新的,不是最新则执行版本更新功能。实现方式主要通过plus.downloader.createDownload
下载apk包,下载完成后通过plus.runtime.install
来进行安装,在下载时给下载任务设置一个监听根据状态实时更新下载进度