uniapp增加在线更新的功能---整体

解决的思路就是,在首页每次检查都记录查询时间,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,
相关推荐
wuxianda103013 小时前
4.3(a) 整改期素材从哪来:外包、素材站、AI 生成的内容怎么留证
uni-app·swift·4.3a·appstore审核
anyup1 天前
【全端支持】 uni-app x 专用请求库:axios 写法,多实例、拦截器、可中断、上传下载
前端·uni-app·unix
anyup3 天前
uView Pro X 2.0 发布:弃用 UTS,全面支持 TypeScript 的 uni-app x 蒸汽模式 UI 框架
前端·uni-app·ai编程
wuxianda10307 天前
uniapp 与跨端打包项目:壳子和框架层默认特征,相似是从哪里来的
uni-app
码间留白7 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
uni-app·harmonyos·鸿蒙·uts插件·微信商家转账
wuxianda10307 天前
苹果 App 上架 4.3(a) 问题解决方案(适用 uniapp、Objective-C、Swift、Flutter 等项目)
uni-app·objective-c·swift
码间留白8 天前
AI 给的两个方案都被我否了:把 startIcon 与启动遮罩做成同一张图,鸿蒙 APP 冷启动零白屏
性能优化·uni-app·ai编程·harmonyos
anyup8 天前
自带 uni-app x 页面级能力,uView Pro X 8 个开箱即用的工具函数
前端·vue.js·uni-app
码间留白14 天前
六轮真机实验后,我把鸿蒙直播推流的 UI 全逼成了原生——uni-app 适配 HarmonyOS NEXT 完整复盘
uni-app·鸿蒙·harmonyos next·直播推流·arkts/arkui
wuxianda103015 天前
2026 苹果审核 4.3 (a) 被拒全解析|Guideline 4.3a spam 马甲包拒审原因 + 避坑方案
flutter·uni-app·苹果上架