首页IT科技uniapp强制更新提示(uniapp 实现app自动更新)

uniapp强制更新提示(uniapp 实现app自动更新)

时间2025-05-28 23:44:40分类IT科技浏览8198
导读:需求概述: 最近遇到的需求,扫码核验的app需要在线自动升级安装(因app简单上不了应用市场,所以调研用在线更新的办法)...

需求概述: 最近遇到的需求,扫码核验的app需要在线自动升级安装(因app简单上不了应用市场,所以调研用在线更新的办法)

第一步:首先需要一个可以更新和获取数据的接口(后端)

比如第一次打包时的版本名称是1.0.1,那第一次将这个1.0.1版本的手动安装到手机上后,后续想要实现自动更新,再次打包的版本名称就必须大于1.0.1(因为本次实现的逻辑就是根据版本名称)

版本号位置:manifest.json >> 基础配置 >> 应用版本名称

当需要更新app的时候,改变版本名称(必须大于上一个版本),开始打包

同时在后端的接口里同步更新你的此次打包的版本名称

第二步:打包后的apk文件需要放在服务器上,然后拿到在服务器上的文件的地址(后续有用) 第三步:开始在App.vue里书写前端逻辑(直接贴代码) onLoad() : 在页面加载的时候触发,只会调用一次,在onLoad() 函数中,可以通过 option获取当前页面路径中的参数 onShow(): 在页面显示时调用,也就是切换页面的时候,或者切入前台的时候触发,可以多次触发

根据自己的需求来确定是写在onShow还是onLoad

原理:获取当前app的版本名称,在onShow触发的时候调接口比对当前app版本名称和线上最新版本名称,如果线上最新版本名称大于当前版本名称则下载最新的apk安装更新

onShow: function() { console.log(App Show) plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) { this.version = widgetInfo.version uni.request({ url: http://xxxx.cczu.edu.cn:8081/api/dict, success: (res) => { function compareVersion(version1, version2) { const newVersion1 = `${version1}`.split(.).length < 3 ? `${version1}`.concat(.0) : `${version1}`; const newVersion2 = `${version2}`.split(.).length < 3 ? `${version2}`.concat(.0) : `${version2}`; //计算版本号大小,转化大小 function toNum(a){ const c = a.toString().split(.); const num_place = ["", "0", "00", "000", "0000"], r = num_place.reverse(); for (let i = 0; i < c.length; i++){ const len=c[i].length; c[i]=r[len]+c[i]; } return c.join(); } // 检测版本号是否需要更新 function checkPlugin(a, b) { const numA = toNum(a); const numB = toNum(b); return numA > numB ? 1 : numA < numB ? -1 : 0; } return checkPlugin(newVersion1 ,newVersion2); } for (let i of res.data.content) { if (i.description === app版本) { // 1代表app新包版本号大于本地版本号 if (compareVersion(i.dictDetails[0].value, this.version) === 1) { uni.showModal({ title: 提示, content: 发现新的应用安装包,点击确定立即更新, success: function (res) { if (res.confirm) { console.log(用户点击确定); uni.showLoading({ title: 更新中…… }) uni.downloadFile({ // 存放最新安装包的地址 url: http://xxxx.xxxx.com/__UNI__xxxx.apk, success: (downloadResult) => { uni.hideLoading(); if (downloadResult.statusCode === 200) { uni.hideLoading(); plus.runtime.install(downloadResult.tempFilePath,{ force: false }, function() { console.log(install success...); plus.runtime.restart(); }, function(e) { uni.hideLoading(); console.error(install fail...); }); } } }); } else if (res.cancel) { console.log(用户点击取消); } } }); } else { } } } } }); }); },

创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!

展开全文READ MORE
织梦发布文章栏目怎么不显示(织梦dedecms编辑文章不更新时间的方法)