update2.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. var wgtVer=null;
  2. var inf;
  3. function plusReady(){
  4. // 获取本地应用资源版本号
  5. plus.runtime.getProperty(plus.runtime.appid,function(inf){
  6. wgtVer=inf.version;
  7. console.log(wgtVer);
  8. checkUpdate();
  9. });
  10. }
  11. if(window.plus){
  12. plusReady();
  13. }else{
  14. document.addEventListener('plusready',plusReady,false);
  15. }
  16. // 检测更新
  17. var checkUrl=API.API_ROOT + "/apk/check.json?time="+new Date().getTime();
  18. function checkUpdate() {
  19. mui.getJSON(checkUrl, {
  20. "appid": plus.runtime.appid,
  21. "version": plus.runtime.version,
  22. "imei": plus.device.imei
  23. }, function(data) {
  24. var curVer = wgtVer,inf = data[plus.os.name];
  25. console.log(inf.url);
  26. if(inf) {
  27. var srvVer = inf.version;
  28. var appVer = API.API_VERSION;
  29. if(compareVersion(curVer, srvVer)) {
  30. plus.nativeUI.confirm(inf.note, function(event) {
  31. if(0 == event.index) {
  32. downWgt(inf.url);
  33. }
  34. }, data.title, ["立即更新", "取  消"]);
  35. }
  36. }else{
  37. mui.toast("校验版本失败");
  38. }
  39. });
  40. }
  41. /**
  42. * 比较版本大小,如果新版本nv大于旧版本ov则返回true,否则返回false
  43. * @param {String} ov
  44. * @param {String} nv
  45. * @return {Boolean}
  46. */
  47. function compareVersion(ov, nv) {
  48. if(!ov || !nv || ov == "" || nv == "") {
  49. return false;
  50. }
  51. var b = false,
  52. ova = ov.split(".", 4),
  53. nva = nv.split(".", 4);
  54. for(var i = 0; i < ova.length && i < nva.length; i++) {
  55. var so = ova[i],
  56. no = parseInt(so),
  57. sn = nva[i],
  58. nn = parseInt(sn);
  59. if(nn > no || sn.length > so.length) {
  60. return true;
  61. } else if(nn < no) {
  62. return false;
  63. }
  64. }
  65. if(nva.length > ova.length && 0 == nv.indexOf(ov)) {
  66. return true;
  67. }
  68. }
  69. function downWgt(url){
  70. plus.nativeUI.showWaiting("正在更新,请稍候...");
  71. wgtUrl = API.API_ROOT + "/"+url;
  72. plus.downloader.createDownload( wgtUrl, {filename:"_doc/update/"}, function(d,status){
  73. if ( status == 200 ) {
  74. installWgt(d.filename); // 安装wgt包
  75. } else {
  76. plus.nativeUI.alert("下载失败!");
  77. openUrl();
  78. }
  79. plus.nativeUI.closeWaiting();
  80. }).start();
  81. }
  82. // 更新应用资源
  83. function installWgt(path){
  84. plus.runtime.install(path,{},function(){
  85. plus.nativeUI.closeWaiting();
  86. plus.nativeUI.alert("更新完成!",function(){
  87. plus.runtime.restart();
  88. });
  89. },function(e){
  90. plus.nativeUI.closeWaiting();
  91. plus.nativeUI.alert("安装文件失败["+e.code+"]:"+e.message);
  92. openUrl();
  93. });
  94. }
  95. function openUrl(){
  96. plus.nativeUI.toast("更新失败,请重新下载应用");
  97. var apkUrl = API.API_ROOT + "/"+ inf.apkUrl;
  98. plus.runtime.openURL(apkUrl);
  99. }