uniapp檢查app更新並下載,監聽下載進度
阿新 • • 發佈:2021-01-17
技術標籤:uni-app
檢查的方法是放在app.vue裡面的
<script>
import { hostCharge } from "util/httpUrl.js"
import Util from "util/util.js"
export default {
onLaunch: function() {
// console.log('App Launch')
//#ifdef APP-PLUS
this.checkUpdateVersion()
//#endif
},
methods: {
//檢查版本更新
async checkUpdateVersion(){
//鎖定螢幕方向
plus.screen.lockOrientation('portrait-primary')
try{
//獲取版本更新
let { data: { data, code, flag, message } } = await Util.httpRequest({
url: `${hostCharge}/check/version`,
data: {
versionCode: uni.getStorageSync('versionCode' )
}
})
if(code === 20000){
uni.showModal({
title: '溫馨提示',
content: `有新的版本可下載${data.versionCode}是否下載?`,
success:(res) => {
if(res.confirm){
console.log(res.confirm)
//判斷手機型別
// 也可以用5+app的方法:plus.os.name.toLowerCase() == 'ios'
if( uni.getSystemInfoSync().platform === 'ios'){
plus.runtime.openURL(data.updateUrl)
} else {
//新建下載任務
var downloadTask = plus.downloader.createDownload(data.updateUrl, {}, (download,status) => {
if(status === 200){
//安裝APK檔案
plus.runtime.install(download.filename, {}, function(error) {
uni.showModal({
showCancle: false,
content: '安裝失敗'
})
})
} else {
uni.showModal({
showCancle: false,
title: '更新失敗!!!'
})
}
})
try {
// 開始下載
downloadTask.start()
//監聽下載
var that = this
var showLoading = plus.nativeUI.showWaiting("正在下載")
downloadTask.addEventListener('statechanged', function(download,status){
switch (download.state) {
case 1:
uni.showToast({
title: '下載中'
})
break;
case 2:
//出現下載彈框和進度
that.$scope.globalData.updateProgress.popup = true
that.$scope.globalData.updateProgress.percent = parseInt(parseFloat(download.downloadedSize) / parseFloat(download.totalSize) * 100)
// uni.showLoading({
// title: `正在下載${that.$scope.globalData.updateProgress.percent}%`
// })
break;
case 3:
plus.nativeUI.closeWaiting()
}
})
} catch (err) {
plus.nativeUI.closeWaiting()
uni.showModal({
showCancle: false,
content: '下載失敗,請稍後重試'
})
}
}
//檢驗過一次版本就加入快取,不再檢測
uni.setStorageSync('isCheckVersion', true)
}
}
})
} else {
uni.showModal({
showCancle: false,
content: message
})
}
} catch(e) {
uni.showModal({
showCancle: false,
content: '獲取資料失敗'
})
}
}
},
globalData: {
userInfo: {},
restaurantData: {},
//下載彈窗和進度條
updateProgress: {
popup: false,
precent: 0
}
}
}
</script>
在首頁的onReady生命週期進行判斷updateProgress的popup,為true的顯示彈框,對precent進行賦值
彈框我就沒展示了,雖然頁面有點醜,哈哈哈