天天看點

利用H5+實作APP線上更新

1 在APP首頁添加以下js代碼

// 擷取本地應用資源版本号
plus.runtime.getProperty(plus.runtime.appid,function(inf){
  wgtVer = inf.version;
//  mui.toast("目前應用版本:"+wgtVer);
  
  // 檢測更新
  checkUpdate(); 
});      
// 檢測更新
var checkUrl = "能夠傳回最新版本的版本号的一個網址";
function checkUpdate(){
//    plus.nativeUI.showWaiting("檢測更新");
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
    switch(xhr.readyState){
      case 4:
      plus.nativeUI.closeWaiting();
      if(xhr.status == 200){
//          console.log("檢測更新成功!:"+xhr.responseText);
        var newVer = xhr.responseText;
        if(wgtVer&&newVer&&(wgtVer != newVer)){
          // 彈出系統确認對話框
          plus.nativeUI.confirm( "确定下載下傳更新?", function(e){
            if(e.index == 0){
              downWgt();  // 下載下傳wgt資源包
//                mui.alert('下載下傳中!') 
            }else{}
          }, "檢測到最新版本", ["下載下傳","取消"] );
        }else{
                plus.nativeUI.toast("目前版本為最新版本!");
//            console.log('沒有可用更新')
        }
      }else{
//          console.log("檢測更新失敗!");
        plus.nativeUI.toast("檢測更新失敗!");
      }
      break;
      default:
      break;
    }
  }
  xhr.open('GET',checkUrl);
  xhr.send();
};      
// 下載下傳wgt檔案
var wgtUrl = "可以直接通路下載下傳wgt檔案的網址";
function downWgt(){
  plus.nativeUI.showWaiting("下載下傳更新");
  plus.downloader.createDownload( wgtUrl , {filename:"_doc/update/"}, function(d,status){
    if ( status == 200 ) { 
      console.log("下載下傳更新成功:"+d.filename);
      installWgt(d.filename); // 安裝wgt資源包
    } else {
      console.log("下載下傳更新失敗!");
      plus.nativeUI.toast("下載下傳更新失敗!");
    }
    plus.nativeUI.closeWaiting();
  }).start();
};      
// 更新應用資源
function installWgt(path){
  plus.nativeUI.showWaiting("安裝更新");
  plus.runtime.install(path,{},function(){
    plus.nativeUI.closeWaiting();
    console.log("安裝更新成功!");
    plus.nativeUI.alert("更新完成!",function(){
    //  更新完成後重新開機應用
      plus.runtime.restart();
    });
  },function(e){
    plus.nativeUI.closeWaiting();
    console.log("安裝更新失敗!["+e.code+"]:"+e.message);
    plus.nativeUI.toast("安裝更新失敗!");
  });
}      

2 生成wgt線上更新資源包

(1)修改版本号

利用H5+實作APP線上更新

(2)修改最新版本更新内容(編寫具體的更新代碼)

(3)生成wgt資源包

功能欄發行選項–>制作移動App資源更新包–>選擇儲存路徑,确定儲存

(4)修改背景最新版本号(我這裡背景用的是python中的Django)