沒(méi)做過(guò)熱更新的啤斗,可能感覺(jué)很難表箭,但是當(dāng)你知道邏輯流程后,就非常簡(jiǎn)單了钮莲。
一免钻、下面先給大家介紹一下流程:
1彼水、打一個(gè)wgt包,放在服務(wù)器上极舔,確保能被訪問(wèn)凤覆。
2、前端獲取到當(dāng)前版本號(hào)拆魏,傳到服務(wù)端
3盯桦、服務(wù)端對(duì)比客戶端傳來(lái)的版本號(hào)和即將更新的版本號(hào),不一致就返回wgt地址
4稽揭、客戶端接收到wgt地址,下載肥卡,安裝即可
二溪掀、具體實(shí)現(xiàn)
1、打wgt包
2步鉴、客戶端代碼
? ? 獲取當(dāng)前版本號(hào)
// #ifdef APP-PLUS // 獲取當(dāng)前項(xiàng)目信息
let that=this;
plus.runtime.getProperty(plus.runtime.appid, function(widgetInfo) {
that.comparisonVersionNo(widgetInfo.version); });
// #endif????
? ? 檢查接口揪胃,是否需要更新,獲取wgt包
comparisonVersionNo(version){
let that=this;
console.log(version);
let data = {
versionNo:version
};
this.$uniRequest.get('/app/comparisonVersionNo', {
data: data
})
.then(res => {
// console.log(222222);
if (res.data.retCode == 'SUCCESS') {
let versionNos=res.data.retData.versionNos;
console.log(versionNos);
let filePath=res.data.retData.filePath;
if(versionNos==1){//服務(wù)器返回1更新氛琢,0則不更新
uni.showModal({
? ? title: '提示',
? ? content: '發(fā)現(xiàn)新版本喊递,是否升級(jí)',
? ? success: function (res) {
? ? // console.log(widgetInfo.version);
? ? ? ? if (res.confirm) {
? ? ? ? ? ? console.log('用戶點(diǎn)擊確定');
? ? ? ? ? ? that.getProperty(filePath);
? ? ? ? } else if (res.cancel) {
? ? ? ? ? ? console.log('用戶點(diǎn)擊取消');
? ? ? ? }
? ? }
});
}
}
})
.catch(error => {
console.log(error);
});
},
下載并升級(jí)
getProperty(getProperty){
let that=this;
// 在線升級(jí)app/熱更新
that.showwri=true;
? ? const downloadTask=uni.downloadFile({ //下載文件
? ? ? ? ? ? ? ? ? ? url: 'https://wechat.zhishidao.com/'+getProperty,
? ? ? ? ? ? ? ? ? ? success: (downloadResult) => {
? ? ? ? ? ? ? ? ? ? // console.log(downloadResult);
? ? ? ? ? ? ? ? ? ? ? ? if (downloadResult.statusCode === 200) {
? ? ? ? ? ? ? ? ? ? ? ? // 更新升級(jí)
? ? ? ? ? ? ? ? ? ? ? ? ? ? plus.runtime.install(downloadResult.tempFilePath, {?
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? force: false
? ? ? ? ? ? ? ? ? ? ? ? ? ? }, function() {
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? // console.log('install success...');
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? that.showwri=false;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? plus.nativeUI.alert("應(yīng)用資源更新完成!",function(){?
? ? ? ? plus.runtime.restart();
? ? });?
? ? ? ? ? ? ? ? ? ? ? ? ? ? }, function(e) {?
? ? ? ? ? ? ? ? ? ? ? ? ? ? that.showwri=false;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? plus.nativeUI.alert("更新失敗阳似,請(qǐng)稍后再試");
? ? ? ? ? ? ? ? ? ? ? ? ? ? });?
? ? ? ? ? ? ? ? ? ? ? ? }?
? ? ? ? ? ? ? ? ? ? }?
? ? ? ? ? ? ? ? });
? ? downloadTask.onProgressUpdate((res) => {//下載文件的進(jìn)度
? ? that.totalBytesWritten=res.totalBytesWritten;//當(dāng)前下載大小
? ? that.progress=res.progress;//當(dāng)前下載比例
? ? that.totalBytesExpectedToWrite=res.totalBytesExpectedToWrite;//
});
},
3骚勘、服務(wù)端實(shí)現(xiàn)
服務(wù)端實(shí)現(xiàn)非常簡(jiǎn)單,大致為:
接收客戶端傳入的版本號(hào)撮奏,然后與數(shù)據(jù)庫(kù)中的版本號(hào)對(duì)吧俏讹,不一致就返回wgt地址及更新信號(hào)。版本號(hào)數(shù)據(jù)庫(kù)手動(dòng)改就好畜吊,如果有更加好的方法泽疆,歡迎補(bǔ)充