实现效果:
点击软件升级后进行更新下载
实现思路:
介绍:前后端一并实现,这里我们的后端示例使用PHP的thinkphp6.0框架
1.后端设置app的版本号,该版本号与前端uniapp应用版本号对应(在manifest.json中),在有新版本以后要将该版本号进行修改。
2.前端带着当前app的版本号请求检查版本接口,查看是否有新版app。
3.有新版本就进行更新,如果没有就提示已是最新版本
实战demo:
前端demo:
<template>
<view>
<button class="cu-btn block shadow bg-gradual-orange margin" @tap="appUpgrade">软件升级</button>
</view>
</template>
<script>
export default {
data() {
return {
}
},
onShow() {
this.initTheme()
},
onReady() {
},
onLoad() {
},
methods: {
/**
* app整包更新检测
*/
appUpgrade() {
//#ifndef APP-PLUS
uni.showToast({
title: '目前只支持Android版本软件更新',
icon: 'none'
})
//#endif
//#ifdef APP-PLUS
uni.getSystemInfo({
success: sysInfo => {
let platform = sysInfo.platform
//获取系统信息,查看app版本号等信息
plus.runtime.getProperty(plus.runtime.appid, (wgtinfo) => {
let params = {
appid: plus.runtime.appid,
// app整数版本号,如110,一定要用versionCode做判断
version: wgtinfo.versionCode, //版本号212
platform: platform
}
//请求后端接口进行版本判断,我现在后端设置的是213号版本,前端是212号版本
this.$apis.checkAndroidVersion(params).then(appRes => {
//code==1代表有新版本更新
if (appRes.code == 1) {
uni.showModal({
title: "下载更新提示",
content: appRes.msg,
showCancel: false,
confirmText: '确定',
success: sucRes => {
if (sucRes.confirm) {
uni.showLoading({
title: '升级中'
});
//使用createDownload方法请求下载url,进行新版apk下载
//url是请求后端检查版本返回的下载地址
var dtask = plus.downloader
.createDownload(
encodeURI(appRes.data
.url), {},
function(d, status) {
// 下载完成
if (status == 200) {
plus.runtime
.install(plus
.io
.convertLocalFileSystemURL(
d
.filename
), {}, {},
function(
error
) {
uni.showToast({
title: '安装失败',
duration: 1500
});
})
} else {
uni.showToast({
title: '更新失败',
duration: 1500
});
}
uni.hideLoading();
});
dtask.start();
uni.downloadFile({
url: appRes.url,
success: res => {}
})
}
}
})
} else {
uni.showToast({
title: '已经是最新版本了。',
icon: 'none'
})
}
})
})
}
})
//#endif
}
}
}
</script>
后端demo:
1.在配置文件中设置Android版本号
<?php
return [
'app_version'=>"213", //app版本更新,随着前端的版本号更改而更改
];
2.编写一个检查版本接口
class Android extends \app\BaseController
{
/**
* 检测版本
*/
public function checkAndroidVersion(){
//获取最新版本号
$serverVersion=config("android.app_version");
//判断当前版本号是否小于最新版本号,如果小于则需要更新
if((int)input('version')<$serverVersion){
return Show::success("可以升级",[
//这里我设置的apk下载地址是apk/test.apk
//有条件的尽量放到OSS,会大大提升更新效率
'url'=>'https://'.$_SERVER['HTTP_HOST'].'/apk/test.apk'
]);
}
return Show::error("已经是最新版本了");
}
}