当前位置:   article > 正文

uniapp校验app版本并更新

uniapp校验app版本并更新

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

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

相关代码

App.vue

  1. <script>
  2. export default {
  3. onLaunch: function() {
  4. this.checkVersion()
  5. },
  6. onShow: function() {
  7. console.log('App Show')
  8. },
  9. onHide: function() {
  10. console.log('App Hide')
  11. },
  12. methods: {
  13. checkVersion() {
  14. //https://www.xxxx.com.cn/api/App/GetAppVersion 用来获取app信息的接口
  15. uni.request({
  16. url: 'https://www.xxxx.com.cn/api/App/GetAppVersion',
  17. method: 'get',
  18. data: {},
  19. header: {
  20. 'Content-Type': 'application/json', // 设置请求头
  21. },
  22. success: (res) => {
  23. console.log('success', res)
  24. if (res.data.Flag == 1) {
  25. let {
  26. Data
  27. } = res.data
  28. if (Data.VersionCode) {
  29. plus.runtime.getProperty(plus.runtime.appid, function(wgtinfo) {
  30. const newVersionCode = Data.VersionCode; //线上最新版本号
  31. const selfVersionCode = wgtinfo.versionCode //当前APP应用版本
  32. console.log('newVersionCode:',newVersionCode)
  33. console.log('selfVersionCode:',selfVersionCode)
  34. //线上版本号和当前不一样,进行在线升级
  35. if (selfVersionCode != newVersionCode) {
  36. let platform = uni.getSystemInfoSync().platform //手机平台
  37. //安卓手机弹窗升级
  38. if (platform === 'android') {
  39. uni.navigateTo({
  40. url: '/pages/upgrade/index'
  41. })
  42. }
  43. }
  44. });
  45. }
  46. }
  47. },
  48. fail: (err) => {
  49. console.log('err', err)
  50. },
  51. });
  52. }
  53. }
  54. }
  55. </script>
  56. <style>
  57. /*每个页面公共css */
  58. </style>

pages下的upgrade    index.vue

  1. <template>
  2. <view class="upgrade-popup">
  3. <!-- <image class="header-bg" src="../../static/upgrade_bg.png" mode="widthFix"></image>-->
  4. <view class="upgrade-main">
  5. <view class="version">发现新版本</view>
  6. <view class="upgrade-content">
  7. <text class="title">更新内容</text>
  8. <view class="desc" v-html="versionDesc"></view>
  9. </view>
  10. <!--下载状态-进度条显示 -->
  11. <view class="footer" v-if="isStartDownload">
  12. <view class="progress-view" :class="{'active':!hasProgress}" @click="handleInstallApp">
  13. <!-- 进度条 -->
  14. <view v-if="hasProgress" style="height: 100%;">
  15. <view class="txt">{{percentText}}</view>
  16. <view class="progress" :style="setProStyle"></view>
  17. </view>
  18. <view v-else>
  19. <view class="btn upgrade force">{{ isDownloadFinish ? '立即安装' :'下载中...'}}</view>
  20. </view>
  21. </view>
  22. </view>
  23. <!-- 强制更新 -->
  24. <view class="footer" v-else-if="isForceUpdate">
  25. <view class="btn upgrade force" @click="handleUpgrade">立即更新</view>
  26. </view>
  27. <!-- 可选择更新 -->
  28. <view class="footer" v-else>
  29. <view class="btn close" @click="handleClose">以后再说</view>
  30. <view class="btn upgrade" @click="handleUpgrade">立即更新</view>
  31. </view>
  32. </view>
  33. </view>
  34. </template>
  35. <script>
  36. import {
  37. downloadApp,
  38. installApp
  39. } from './upgrade.js'
  40. export default {
  41. data() {
  42. return {
  43. isForceUpdate: false, //是否强制更新
  44. versionName: '', //版本名称
  45. versionDesc: '', //更新说明
  46. downloadUrl: '', //APP下载链接
  47. isDownloadFinish: false, //是否下载完成
  48. hasProgress: false, //是否能显示进度条
  49. currentPercent: 0, //当前下载百分比
  50. isStartDownload: false, //是否开始下载
  51. fileName: '', //下载后app本地路径名称
  52. }
  53. },
  54. computed: {
  55. //设置进度条样式,实时更新进度位置
  56. setProStyle() {
  57. return {
  58. width: (290 * this.currentPercent / 100) + 'px' //510:按钮进度条宽度
  59. }
  60. },
  61. //百分比文字
  62. percentText() {
  63. let percent = this.currentPercent;
  64. if (typeof percent !== 'number' || isNaN(percent)) return '下载中...'
  65. if (percent < 100) return `下载中${percent}%`
  66. return '立即安装'
  67. }
  68. },
  69. onLoad() {
  70. this.init()
  71. },
  72. onBackPress(options) {
  73. // 禁用返回
  74. if (options.from == 'backbutton') {
  75. return true;
  76. }
  77. },
  78. methods: {
  79. //初始化获取最新APP版本信息
  80. init() {
  81. uni.request({
  82. url: 'https://www.xxxx.com.cn/api/App/GetAppVersion',
  83. method: 'get',
  84. data: {},
  85. header: {
  86. 'Content-Type': 'application/json', // 设置请求头
  87. },
  88. success: (res) => {
  89. console.log('success', res)
  90. if (res.data.Flag == 1) {
  91. let {
  92. Data
  93. } = res.data
  94. if (Data.VersionCode) {
  95. this.versionName = Data.VersionCode; //版本名称
  96. this.versionDesc = Data.Describe; //更新说明
  97. this.downloadUrl = Data.Url; //下载链接
  98. this.isForceUpdate = false; //是否强制更新
  99. }
  100. }
  101. },
  102. fail: (err) => {
  103. console.log('err', err)
  104. },
  105. });
  106. },
  107. //更新
  108. handleUpgrade() {
  109. if (this.downloadUrl) {
  110. this.isStartDownload = true
  111. //开始下载App
  112. downloadApp(this.downloadUrl, current => {
  113. //下载进度监听
  114. this.hasProgress = true
  115. this.currentPercent = current
  116. }).then(fileName => {
  117. //下载完成
  118. this.isDownloadFinish = true
  119. this.fileName = fileName
  120. if (fileName) {
  121. //自动安装App
  122. this.handleInstallApp()
  123. }
  124. }).catch(e => {
  125. console.log(e, 'e')
  126. })
  127. } else {
  128. uni.showToast({
  129. title: '下载链接不存在',
  130. icon: 'none'
  131. })
  132. }
  133. },
  134. //安装app
  135. handleInstallApp() {
  136. //下载完成才能安装,防止下载过程中点击
  137. if (this.isDownloadFinish && this.fileName) {
  138. installApp(this.fileName, () => {
  139. //安装成功,关闭升级弹窗
  140. uni.navigateBack()
  141. })
  142. }
  143. },
  144. //关闭返回
  145. handleClose() {
  146. uni.navigateBack()
  147. // uni.navigateTo({
  148. // url: '/pages/login/index'
  149. // })
  150. },
  151. }
  152. }
  153. </script>
  154. <style>
  155. page {
  156. background: rgba(0, 0, 0, 0.5);/**设置窗口背景半透明*/
  157. }
  158. </style>
  159. <style lang="scss" scoped>
  160. .upgrade-popup {
  161. width: 290px;
  162. height: auto;
  163. position: fixed;
  164. top: 50%;
  165. left: 50%;
  166. transform: translate(-50%, -50%);
  167. background: #fff;
  168. border-radius: 10px;
  169. box-sizing: border-box;
  170. border: 1px solid #eee;
  171. }
  172. .header-bg {
  173. width: 100%;
  174. margin-top: -112rpx;
  175. }
  176. .upgrade-main {
  177. padding: 5px 15px 15px;
  178. box-sizing: border-box;
  179. .version {
  180. font-size: 18px;
  181. color: #026DF7;
  182. font-weight: 700;
  183. width: 100%;
  184. text-align: center;
  185. overflow: hidden;
  186. text-overflow: ellipsis;
  187. white-space: nowrap;
  188. letter-spacing: 1px;
  189. }
  190. .upgrade-content {
  191. margin-top: 30px;
  192. .title {
  193. font-size: 14px;
  194. font-weight: 700;
  195. color: #000000;
  196. }
  197. .desc {
  198. box-sizing: border-box;
  199. margin-top: 10px;
  200. font-size: 14px;
  201. color: #6A6A6A;
  202. max-height: 80vh;
  203. overflow-y: auto;
  204. }
  205. }
  206. .footer {
  207. width: 100%;
  208. display: flex;
  209. justify-content: center;
  210. align-items: center;
  211. position: relative;
  212. flex-shrink: 0;
  213. margin-top: 50px;
  214. .btn {
  215. width: 123px;
  216. display: flex;
  217. justify-content: center;
  218. align-items: center;
  219. position: relative;
  220. z-index: 999;
  221. height: 48px;
  222. box-sizing: border-box;
  223. font-size: 16px;
  224. border-radius: 5px;
  225. letter-spacing: 1px;
  226. &.force {
  227. width: 250px;
  228. }
  229. &.close {
  230. border: 1px solid #E0E0E0;
  231. margin-right: 12px;
  232. color: #000;
  233. }
  234. &.upgrade {
  235. background-color: #026DF7;
  236. color: white;
  237. }
  238. }
  239. .progress-view {
  240. width: 255px;
  241. height: 24px;
  242. display: flex;
  243. position: relative;
  244. align-items: center;
  245. border-radius: 3px;
  246. background-color: #dcdcdc;
  247. display: flex;
  248. justify-content: flex-start;
  249. padding: 0px;
  250. box-sizing: border-box;
  251. border: none;
  252. overflow: hidden;
  253. &.active {
  254. background-color: #026DF7;
  255. }
  256. .progress {
  257. height: 100%;
  258. background-color: #026DF7;
  259. padding: 0px;
  260. box-sizing: border-box;
  261. border: none;
  262. border-top-left-radius: 5px;
  263. border-bottom-left-radius: 5px;
  264. }
  265. .txt {
  266. font-size: 14px;
  267. position: absolute;
  268. top: 50%;
  269. left: 50%;
  270. transform: translate(-50%, -50%);
  271. color: #fff;
  272. }
  273. }
  274. }
  275. }
  276. </style>

pages下的upgrade    upgrade.js

  1. export const downloadApp = (downloadUrl, progressCallBack = () => {}, ) => {
  2. return new Promise((resolve, reject) => {
  3. //创建下载任务
  4. const downloadTask = plus.downloader.createDownload(downloadUrl, {
  5. method: "GET"
  6. }, (task, status) => {
  7. console.log(status,'status')
  8. if (status == 200) { //下载成功
  9. resolve(task.filename)
  10. } else {
  11. reject('fail')
  12. uni.showToast({
  13. title: '下载失败',
  14. duration: 1500,
  15. icon: "none"
  16. });
  17. }
  18. })
  19. //监听下载过程
  20. downloadTask.addEventListener("statechanged", (task, status) => {
  21. switch (task.state) {
  22. case 1: // 开始
  23. break;
  24. case 2: //已连接到服务器
  25. break;
  26. case 3: // 已接收到数据
  27. let hasProgress = task.totalSize && task.totalSize > 0 //是否能获取到App大小
  28. if (hasProgress) {
  29. let current = parseInt(100 * task.downloadedSize / task.totalSize); //获取下载进度百分比
  30. progressCallBack(current)
  31. }
  32. break;
  33. case 4: // 下载完成
  34. break;
  35. }
  36. });
  37. //开始执行下载
  38. downloadTask.start();
  39. })
  40. }
  41. /**
  42. * @description H5+安装APP
  43. * @param fileName:app文件名
  44. * @param callBack:安装成功回调
  45. */
  46. export const installApp = (fileName, callBack = () => {}) => {
  47. //注册广播监听app安装情况
  48. onInstallListening(callBack);
  49. //开始安装
  50. plus.runtime.install(plus.io.convertLocalFileSystemURL(fileName), {}, () => {
  51. //成功跳转到安装界面
  52. }, function(error) {
  53. uni.showToast({
  54. title: '安装失败',
  55. duration: 1500,
  56. icon: "none"
  57. });
  58. })
  59. }
  60. /**
  61. * @description 注册广播监听APP是否安装成功
  62. * @param callBack:安装成功回调函数
  63. */
  64. const onInstallListening = (callBack = () => {}) => {
  65. let mainActivity = plus.android.runtimeMainActivity(); //获取activity
  66. //生成广播接收器
  67. let receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
  68. onReceive: (context, intent) => { //接收广播回调
  69. plus.android.importClass(intent);
  70. mainActivity.unregisterReceiver(receiver); //取消监听
  71. callBack()
  72. }
  73. });
  74. let IntentFilter = plus.android.importClass('android.content.IntentFilter');
  75. let Intent = plus.android.importClass('android.content.Intent');
  76. let filter = new IntentFilter();
  77. filter.addAction(Intent.ACTION_PACKAGE_ADDED); //监听APP安装
  78. filter.addDataScheme("package");
  79. mainActivity.registerReceiver(receiver, filter); //注册广播
  80. }

pages.json 

  1. {
  2. "pages": [ //pages数组中第一项表示应用启动页,参考:https://uniapp.dcloud.io/collocation/pages
  3. {
  4. "path": "pages/index/index",
  5. "style": {
  6. "navigationStyle": "custom"
  7. }
  8. },
  9. {
  10. "path": "pages/upgrade/index", //升级窗口页面
  11. "style": {
  12. "navigationBarTitleText": "",
  13. "navigationStyle": "custom",
  14. "app-plus": {
  15. "bounce": "none",
  16. "animationType":"none", //取消窗口动画
  17. "background": "transparent" // 设置背景透明
  18. }
  19. }
  20. }
  21. ],
  22. "globalStyle": {
  23. "navigationBarTextStyle": "black",
  24. // "navigationBarTitleText": "uni-app",
  25. "navigationBarBackgroundColor": "#F8F8F8",
  26. "backgroundColor": "#F8F8F8"
  27. },
  28. "uniIdRouter": {}
  29. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/122115
推荐阅读
相关标签
  

闽ICP备14008679号