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,
相关推荐
不爱说话郭德纲6 小时前
告别漫长的HbuilderX云打包排队!uni-app x 安卓本地打包保姆级教程(附白屏、包体积过大排坑指南)
android·前端·uni-app
HashTang1 天前
【AI 编程实战】第 12 篇:从 0 到 1 的回顾 - 项目总结与 AI 协作心得
前端·uni-app·ai编程
JunjunZ2 天前
uniapp 文件预览:从文件流到多格式预览的完整实现
前端·uni-app
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
TT_Close2 天前
“啪啪啪”三下键盘,极速拉起你的 uni-app 项目!
vue.js·uni-app·前端工程化
特立独行的猫a2 天前
uni-app x跨平台开发实战:开发鸿蒙HarmonyOS影视票房榜组件完整实现过程
华为·uni-app·harmonyos·轮播图·uniapp-x
00后整顿职场3 天前
Hbuilderx APP真机无法识别iqoo Z9+手机设备解决方案
uni-app·uniapp真机调试·真机运行
前端小雪的博客.3 天前
【保姆级教程】uniAI 插件高效开发 uni-app 微信小程序(附实战案例)
微信小程序·uni-app·ai编程·uniai
T^T尚3 天前
一个完整的项目怎么打包成为一个app
前端·uni-app
阿巴资源站3 天前
uniapp加水印
java·前端·uni-app