uniapp校验app版本并更新

news/2024/9/22 12:06:19/

最近用uniapp写了一个安卓壳子做app,遇到一个需求,校验app版本并更新

通过对比线上版本号和app自己的版本号的差异,唤起更新弹窗

相关代码

App.vue

<script>export default {onLaunch: function() {this.checkVersion()},onShow: function() {console.log('App Show')},onHide: function() {console.log('App Hide')},methods: {checkVersion() {
//https://www.xxxx.com.cn/api/App/GetAppVersion   用来获取app信息的接口uni.request({url: 'https://www.xxxx.com.cn/api/App/GetAppVersion',method: 'get',data: {},header: {'Content-Type': 'application/json', // 设置请求头},success: (res) => {console.log('success', res)if (res.data.Flag == 1) {let {Data} = res.dataif (Data.VersionCode) {plus.runtime.getProperty(plus.runtime.appid, function(wgtinfo) {const newVersionCode = Data.VersionCode; //线上最新版本号const selfVersionCode = wgtinfo.versionCode //当前APP应用版本console.log('newVersionCode:',newVersionCode)console.log('selfVersionCode:',selfVersionCode)//线上版本号和当前不一样,进行在线升级if (selfVersionCode != newVersionCode) {let platform = uni.getSystemInfoSync().platform //手机平台//安卓手机弹窗升级if (platform === 'android') {uni.navigateTo({url: '/pages/upgrade/index'})}}});}}},fail: (err) => {console.log('err', err)},});}}}
</script><style>/*每个页面公共css */
</style>

pages下的upgrade    index.vue

<template><view class="upgrade-popup">
<!--    <image class="header-bg" src="../../static/upgrade_bg.png" mode="widthFix"></image>--><view class="upgrade-main"><view class="version">发现新版本</view><view class="upgrade-content"><text class="title">更新内容</text><view class="desc" v-html="versionDesc"></view></view><!--下载状态-进度条显示 --><view class="footer" v-if="isStartDownload"><view class="progress-view" :class="{'active':!hasProgress}" @click="handleInstallApp"><!-- 进度条 --><view v-if="hasProgress" style="height: 100%;"><view class="txt">{{percentText}}</view><view class="progress" :style="setProStyle"></view></view><view v-else><view class="btn upgrade force">{{ isDownloadFinish  ? '立即安装' :'下载中...'}}</view></view></view></view><!-- 强制更新 --><view class="footer" v-else-if="isForceUpdate"><view class="btn upgrade force" @click="handleUpgrade">立即更新</view></view><!-- 可选择更新 --><view class="footer" v-else><view class="btn close" @click="handleClose">以后再说</view><view class="btn upgrade" @click="handleUpgrade">立即更新</view></view></view></view>
</template><script>
import {downloadApp,installApp
} from './upgrade.js'
export default {data() {return {isForceUpdate: false, //是否强制更新versionName: '', //版本名称versionDesc: '', //更新说明downloadUrl: '', //APP下载链接isDownloadFinish: false, //是否下载完成hasProgress: false, //是否能显示进度条currentPercent: 0, //当前下载百分比isStartDownload: false, //是否开始下载fileName: '', //下载后app本地路径名称}},computed: {//设置进度条样式,实时更新进度位置setProStyle() {return {width: (290 * this.currentPercent / 100) + 'px' //510:按钮进度条宽度}},//百分比文字percentText() {let percent = this.currentPercent;if (typeof percent !== 'number' || isNaN(percent)) return '下载中...'if (percent < 100) return `下载中${percent}%`return '立即安装'}},onLoad() {this.init()},onBackPress(options) {// 禁用返回if (options.from == 'backbutton') {return true;}},methods: {//初始化获取最新APP版本信息init() {uni.request({url: 'https://www.xxxx.com.cn/api/App/GetAppVersion',method: 'get',data: {},header: {'Content-Type': 'application/json', // 设置请求头},success: (res) => {console.log('success', res)if (res.data.Flag == 1) {let {Data} = res.dataif (Data.VersionCode) {this.versionName = Data.VersionCode; //版本名称this.versionDesc = Data.Describe; //更新说明this.downloadUrl = Data.Url; //下载链接this.isForceUpdate = false; //是否强制更新}}},fail: (err) => {console.log('err', err)},});},//更新handleUpgrade() {if (this.downloadUrl) {this.isStartDownload = true//开始下载AppdownloadApp(this.downloadUrl, current => {//下载进度监听this.hasProgress = truethis.currentPercent = current}).then(fileName => {//下载完成this.isDownloadFinish = truethis.fileName = fileNameif (fileName) {//自动安装Appthis.handleInstallApp()}}).catch(e => {console.log(e, 'e')})} else {uni.showToast({title: '下载链接不存在',icon: 'none'})}},//安装apphandleInstallApp() {//下载完成才能安装,防止下载过程中点击if (this.isDownloadFinish && this.fileName) {installApp(this.fileName, () => {//安装成功,关闭升级弹窗uni.navigateBack()})}},//关闭返回handleClose() {uni.navigateBack()// uni.navigateTo({//   url: '/pages/login/index'// })},}
}
</script><style>
page {background: rgba(0, 0, 0, 0.5);/**设置窗口背景半透明*/
}
</style>
<style lang="scss" scoped>
.upgrade-popup {width: 290px;height: auto;position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);background: #fff;border-radius: 10px;box-sizing: border-box;border: 1px solid #eee;
}.header-bg {width: 100%;margin-top: -112rpx;
}.upgrade-main {padding: 5px 15px 15px;box-sizing: border-box;.version {font-size: 18px;color: #026DF7;font-weight: 700;width: 100%;text-align: center;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;letter-spacing: 1px;}.upgrade-content {margin-top: 30px;.title {font-size: 14px;font-weight: 700;color: #000000;}.desc {box-sizing: border-box;margin-top: 10px;font-size: 14px;color: #6A6A6A;max-height: 80vh;overflow-y: auto;}}.footer {width: 100%;display: flex;justify-content: center;align-items: center;position: relative;flex-shrink: 0;margin-top: 50px;.btn {width: 123px;display: flex;justify-content: center;align-items: center;position: relative;z-index: 999;height: 48px;box-sizing: border-box;font-size: 16px;border-radius: 5px;letter-spacing: 1px;&.force {width: 250px;}&.close {border: 1px solid #E0E0E0;margin-right: 12px;color: #000;}&.upgrade {background-color: #026DF7;color: white;}}.progress-view {width: 255px;height: 24px;display: flex;position: relative;align-items: center;border-radius: 3px;background-color: #dcdcdc;display: flex;justify-content: flex-start;padding: 0px;box-sizing: border-box;border: none;overflow: hidden;&.active {background-color: #026DF7;}.progress {height: 100%;background-color: #026DF7;padding: 0px;box-sizing: border-box;border: none;border-top-left-radius: 5px;border-bottom-left-radius: 5px;}.txt {font-size: 14px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);color: #fff;}}}
}
</style>

pages下的upgrade    upgrade.js

export const downloadApp = (downloadUrl, progressCallBack = () => {}, ) => {return new Promise((resolve, reject) => {//创建下载任务const downloadTask = plus.downloader.createDownload(downloadUrl, {method: "GET"}, (task, status) => {console.log(status,'status')if (status == 200) { //下载成功resolve(task.filename)} else {reject('fail')uni.showToast({title: '下载失败',duration: 1500,icon: "none"});}})//监听下载过程downloadTask.addEventListener("statechanged", (task, status) => {switch (task.state) {case 1: // 开始break;case 2: //已连接到服务器break;case 3: // 已接收到数据let hasProgress = task.totalSize && task.totalSize > 0 //是否能获取到App大小if (hasProgress) {let current = parseInt(100 * task.downloadedSize / task.totalSize); //获取下载进度百分比progressCallBack(current)}break;case 4: // 下载完成break;}});//开始执行下载downloadTask.start();})
}
/*** @description H5+安装APP* @param fileName:app文件名* @param callBack:安装成功回调*/
export const installApp = (fileName, callBack = () => {}) => {//注册广播监听app安装情况onInstallListening(callBack);//开始安装plus.runtime.install(plus.io.convertLocalFileSystemURL(fileName), {}, () => {//成功跳转到安装界面}, function(error) {uni.showToast({title: '安装失败',duration: 1500,icon: "none"});})}
/*** @description 注册广播监听APP是否安装成功* @param callBack:安装成功回调函数*/
const onInstallListening = (callBack = () => {}) => {let mainActivity = plus.android.runtimeMainActivity(); //获取activity//生成广播接收器let receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {onReceive: (context, intent) => { //接收广播回调plus.android.importClass(intent);mainActivity.unregisterReceiver(receiver); //取消监听callBack()}});let IntentFilter = plus.android.importClass('android.content.IntentFilter');let Intent = plus.android.importClass('android.content.Intent');let filter = new IntentFilter();filter.addAction(Intent.ACTION_PACKAGE_ADDED); //监听APP安装filter.addDataScheme("package");mainActivity.registerReceiver(receiver, filter); //注册广播}

pages.json 

{"pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages{"path": "pages/index/index","style": {"navigationStyle": "custom"}},{"path": "pages/upgrade/index", //升级窗口页面"style": {"navigationBarTitleText": "","navigationStyle": "custom","app-plus": {"bounce": "none","animationType":"none", //取消窗口动画"background": "transparent" // 设置背景透明}}}],"globalStyle": {"navigationBarTextStyle": "black",// "navigationBarTitleText": "uni-app","navigationBarBackgroundColor": "#F8F8F8","backgroundColor": "#F8F8F8"},"uniIdRouter": {}
}


http://www.ppmy.cn/news/1356734.html

相关文章

领先一步:2024年大广赛设计趋势预测

2024年大赛已经开始&#xff01;作为最具影响力的学科竞赛项目之一&#xff0c;中国大学生好创意全国大学生广告艺术大赛&#xff08;以下简称“大广赛”&#xff09;自2005年以来已举办12届13届大赛&#xff0c;是权威机构认可的以“创意”为核心理念、以“创新”为教育目标的…

第3.2章:Doris-2.0数据导入——Compaction机制

目录 一、Compaction概述 1.1 LSM-Tree概述 1.2 Compaction概述 1.3 Rowset数据版本 1.4 Compaction优点 1.5 Compaction问题 1.5.1 Compaction速度低 1.5.2 写放大问题 1.6 Compaction调优 1.6.1 业务侧 1.6.2 运维侧 二、Compaction执行方式 2.1 Vertical Com…

Linux 内存top命令详解

通过top命令可以监控当前机器的内存实时使用情况&#xff0c;该命令的参数解释如下&#xff1a; 第一行 15:30:14 —— 当前系统时间 up 1167 days, 5:02 —— 系统已经运行的时长&#xff0c;格式为时:分 1 users ——当前有1个用户登录系统 load average: 0.00, 0.01, 0.05…

通用二进制方式安装MySQL8.0.x

一、必要说明 1、系统&#xff1a;openEuler操作系统 2、版本&#xff1a;MySQL - 8.0.36 3、下载地址&#xff1a;https://dev.mysql.com/get/Downloads/MySQL-8.0 二、安装步骤 1、下载glibc版本的Mysql [rootnode2 ~]# wget -c https://dev.mysql.com/get/Downloads/MySQ…

elementUI 动态校验表单数据的方法

elementUI 动态校验表单数据的方法 直接设置如下 list 为动态获取的数据值列表数据 这里主要设置两块内容 prop为动态数据 rules设置需要校验的值 :prop“list.${index}.title” :rules“rules.title” //title 名称可自己定义 //这里主要设置两块内容 prop为动态数据 rules…

【计算机网络】第六章·应用层

目录 1.应用层概述 1.1.客户/服务器方式和对等方式 1.客户/服务器方式&#xff08;C/S方式&#xff09; 2.对等方式&#xff08;P2P方式&#xff09; 1.2.动态主机配置协议DHCP 2.域名系统DNS 2.1.DNS的作用 2.2.层次树状结构的域名结构 2.3.因特网上的域名服务器 2.…

提升数据库操作技能:发现MyBatis-Plus学习网站的无限可能!

介绍&#xff1a;MyBatis-Plus是一个对MyBatis框架进行增强的工具&#xff0c;旨在简化开发流程并提升开发效率。以下是MyBatis-Plus的一些主要特点&#xff1a; CRUD操作简化&#xff1a;MyBatis-Plus提供了一些列的CRUD操作方法&#xff0c;这些方法已经封装好&#xff0c;可…

猫多喝水好吗?拿捏住了这些办法让猫咪乖乖喝水

猫多喝水好吗&#xff1f;充足的水分摄入对猫咪的健康非常重要&#xff0c;有助于维持其体液平衡&#xff0c;促进消化&#xff0c;降低便秘的风险&#xff0c;并保护泌尿系统的健康。猫多喝水好吗&#xff1f;建议每公斤体重的猫每天摄入60-80毫升的水&#xff0c;除了与体重相…