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,
相关推荐
喵喵虫18 小时前
uniapp修改封装组件失败 styleIsolation
uni-app
游戏开发爱好者81 天前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 天前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106321 天前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
宠友信息1 天前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
“负拾捌”1 天前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别
局外人LZ2 天前
Uniapp脚手架项目搭建,uniapp+vue3+uView pro+vite+pinia+sass
前端·uni-app·sass
2501_915918412 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
前端呆头鹅2 天前
Websocket使用方案详解(uniapp版)
websocket·网络协议·uni-app
浮桥2 天前
uniapp+h5 公众号实现分享海报绘制
uni-app·notepad++