利用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)修改版本号
(2)修改最新版本更新内容(编写具体的更新代码)
(3)生成wgt资源包
功能栏发行选项–>制作移动App资源升级包–>选择保存路径,确定保存
(4)修改后台最新版本号(我这里后台用的是python中的Django)
(5)将生成的wgt放在通过一个网址可以直接访问下载的地方
注:在制作wgt资源包的时候一定要断开真机调试,避免修改端口号之后,当前真机运行版本已是最新版本,测试不出效果