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,
相关推荐
郑州光合科技余经理1 小时前
开发实战:海外版同城o2o生活服务平台核心模块设计
开发语言·git·python·架构·uni-app·生活·智慧城市
行走的陀螺仪2 小时前
在UniApp H5中,实现路由栈的持久化
前端·javascript·uni-app·路由持久化·路由缓存策略
影子打怪2 小时前
uniapp通过plus.geolocation.watchPosition获取的坐标格式转换
uni-app
忒可君2 小时前
2026新年第一篇:uni-app + AI = 3分钟实现数据大屏
前端·vue.js·uni-app
行走的陀螺仪2 小时前
UniApp 横向可滚动 Tab 组件开发详解
uni-app·封装组件·tabs·自定义封装组件·可滚动组件tab
2501_915918412 小时前
介绍如何在电脑上查看 iPhone 和 iPad 的完整设备信息
android·ios·小程序·uni-app·电脑·iphone·ipad
2501_916008892 小时前
没有 Mac 如何在 Windows 上创建 iOS 应用描述文件
android·macos·ios·小程序·uni-app·iphone·webview
Rysxt_13 小时前
uni-app路由跳转完全指南:从基础到高级实践
uni-app
一壶纱18 小时前
UniApp + Pinia 数据持久化
前端·数据库·uni-app
酒醉的胡铁1 天前
uniapp解决video组件在ios上全屏页面旋转90度,组件旋转180度
ios·uni-app