解决的思路就是,在首页每次检查都记录查询时间,24小时间隔检查。
将获取版本的逻辑封装 upgrade.js
js
export default {
// 检查更新
checkUpdate(versionUrl) {
return new Promise((resolve, reject) => {
uni.request({
url: versionUrl,
method: 'GET',
success: (res) => {
if (res.statusCode === 200 && res.data.code === 200) {
plus.runtime.getProperty(plus.runtime.appid, (inf) => {
//var it= JSON.stringify(inf)
const serverVersion = res.data.data.version;
const currentVersion = inf['version']
console.log(currentVersion)
if (this.compareVersion(serverVersion, currentVersion) > 0) {
resolve({
hasUpdate: true,
versionInfo: res.data.data
});
} else {
resolve({
hasUpdate: false
});
}
});
} else {
reject(new Error('获取版本信息失败'));
}
},
fail: (err) => {
reject(err);
}
});
});
},
// 比较版本号
compareVersion(v1, v2) {
const v1Arr = v1.split('.').map(Number);
const v2Arr = v2.split('.').map(Number);
const len = Math.max(v1Arr.length, v2Arr.length);
for (let i = 0; i < len; i++) {
const num1 = v1Arr[i] || 0;
const num2 = v2Arr[i] || 0;
if (num1 > num2) return 1;
if (num1 < num2) return -1;
}
return 0;
},
// 下载并安装更新包
downloadAndInstall(updateUrl, onProgress) {
return new Promise((resolve, reject) => {
const dtask = plus.downloader.createDownload(
updateUrl,
{
filename: '_doc/update/' + Date.now() + '.apk'
},
(d, status) => {
if (status === 200) {
this.installPackage(d.filename);
resolve(d.filename);
} else {
reject(new Error('下载失败'));
}
}
);
// 监听下载进度
dtask.addEventListener('statechanged', (task, status) => {
switch (task.state) {
case 3: // 下载中
const progress = parseInt((task.downloadedSize / task.totalSize) * 100);
if (onProgress && typeof onProgress === 'function') {
onProgress(progress);
}
break;
case 4: // 下载完成
break;
}
});
dtask.start();
});
},
// 安装APK(Android)
installPackage(filePath) {
if (uni.getSystemInfoSync().platform === 'android') {
plus.runtime.install(
filePath,
{
force: false
},
function(widgetInfo) {
console.log('安装成功:', widgetInfo);
},
function(error) {
console.log('安装失败:', error);
}
);
}
}
};
相关方法需要增加
js
closeup(){
this.showwarn=false
},
async checkForUpdate() {
try {
uni.showLoading({ title: '检查更新中...' });
const result = await upgrade.checkUpdate(this.versionUrl);
uni.hideLoading();
if (result.hasUpdate) {
this.versionInfo = result.versionInfo;
this.updateUrl = result.versionInfo.download_url;
this.forceUpdate = result.versionInfo.force_update || false;
// 显示更新弹窗
//this.$refs.upgradePopup.open();
this.showwarn=true
// 如果是强制更新,禁用返回键
if (this.forceUpdate) {
this.disableBackButton();
}
} else {
uni.showToast({
title: '当前已是最新版本',
icon: 'success'
});
}
} catch (error) {
uni.hideLoading();
uni.showToast({
title: '检查更新失败',
icon: 'none'
});
console.error('检查更新失败:', error);
}
},
throttledCheck() {
const now = Date.now()
const lastCheck = uni.getStorageSync('last_version_check') || 0
console.log(now - lastCheck)
if(lastCheck!=0){
// 至少间隔4小时才执行一次前台检查
if (now - lastCheck >24*60*60*1000) {
uni.setStorageSync('last_version_check', now)
this.checkForUpdate()
}
}else{
uni.setStorageSync('last_version_check', now)
}
},
// 开始升级
async startUpgrade() {
try {
this.downloading = true;
this.downloadProgress = 0;
await upgrade.downloadAndInstall(
this.updateUrl,
(progress) => {
this.downloadProgress = progress;
}
);
uni.showToast({
title: '下载完成,开始安装',
icon: 'success'
});
} catch (error) {
uni.showToast({
title: '下载失败,请重试',
icon: 'none'
});
console.error('下载失败:', error);
} finally {
this.downloading = false;
}
},
// 取消更新
cancelUpgrade() {
if (!this.forceUpdate) {
this.showwarn=false
this.enableBackButton();
}
},
// 禁用返回按钮
disableBackButton() {
// #ifdef APP-PLUS
plus.key.addEventListener('backbutton', () => {
// 不执行任何操作,阻止返回
});
// #endif
},
// 启用返回按钮
enableBackButton() {
// #ifdef APP-PLUS
plus.key.removeEventListener('backbutton');
// #endif
},
增加组件为:
html
<u-popup :show="showwarn" mode="center" :round="10" :closeable="true" @close="closeup">
<view class="upgrade-content">
<view class="upgrade-header">
<text class="version-text">发现新版本 {{versionInfo.version}}</text>
</view>
<scroll-view class="update-log" scroll-y>
<text class="log-title">更新内容:</text>
<text class="log-content">{{versionInfo.description}}</text>
</scroll-view>
<view class="progress-container" v-if="downloading">
<text class="progress-text">下载进度:{{downloadProgress}}%</text>
<progress
:percent="downloadProgress"
show-info
activeColor="#007AFF"
backgroundColor="#f0f0f0"
/>
</view>
<view class="button-group">
<button
class="btn-cancel"
@click="cancelUpgrade"
v-if="!forceUpdate"
>
稍后更新
</button>
<button
class="btn-upgrade"
@click="startUpgrade"
:disabled="downloading"
>
{{downloading ? '下载中...' : '立即更新'}}
</button>
</view>
</view>
</u-popup>
引用
js
import upgrade from '@/config/upgrade.js';
相关数据
js
versionUrl: '/version', // 版本检查接口 后端域名 接口 路径
updateUrl: '', // 更新包下载地址
versionInfo: {}, // 版本信息
downloading: false, // 是否正在下载
downloadProgress: 0, // 下载进度
forceUpdate: false, // 是否强制更新
showwarn:false,