HBuilderX开发app实现自动更新版本

  需求说明:使用MUI+Vue等技术并且通过HBuilderX打包开发移动app,在有版本更新时需要自动提示用户有新版本,并且可以点击下载自动安装。

思路说明:

  1. 应用打开时(使用Vue的生命周期mounted),获取自己的版本信息appinfo;
    (本身app的信息一般存放在mainfest.json中,直接获取即可)
mui.plusReady(function(){
    mui.getJSON("manifest.json", null, function(manifest){
        var version = data.version
		var vercode_local = version.code;
		var vername_local = version.name;
		console.log("版本名称:"+vername_local+",版本code:"+vercode_local);
    });
});
  1. 获取remote服务器上移动应用最新的版本信息(一般是存放一个json的数据信息)
mui.getJSON(【服务器的url + appInfo.version_json】, null, function(data) {
	var verCode = data.verCode;
	var verName = data.verName;
	//服务器版本
	//console.log("服务器版本名称:"+verName +",服务器版本code:"+verCode);		
});

  1. 判断两个版本号是否相等,不相等则需要更新
if(vercode_local == verCode) {
		mui.toast("当前已经是最新版本!");
	} else {
		var btnArray = ['是', '否'];
		mui.confirm('当前版本是:' + vername_local + ',  最新版本是:' + verName + ',  是否立即更新?', '发现最新版本', btnArray, function(z) {
			if(z.index == 0) {
				console.log('确定');
				installApk(BASEINFO.maxsvc + appInfo.version_apk);
			} else {
				console.log('不确定');
				return;
			}
		});
	}

1.在vue的mounted生命周期进行更新校验

mounted() {
	mui.plusReady(function() {					
		//console.log("检查更新!!!!");
		mui.init({statusBarBackground: '#EEEEEE'});
		plus.screen.lockOrientation("landscape-primary");
		if(mui.os.android) {
			mui.getJSON("../../manifest.json", null, function(data) {
				var version = data.version
				var vercode_local = version.code;
				var vername_local = version.name;
				//当前版本
				//console.log("版本名称:"+vername_local+",版本code:"+vercode_local);
				mui.getJSON(BASEINFO.maxsvc + appInfo.version_json, null, function(data) {
					var verCode = data.verCode;
					//服务器版本
					//console.log("服务器版本code:"+verCode);
					var verName = data.verName;
					if(vercode_local == verCode) {
						mui.toast("当前已经是最新版本!");
					} else {
						var btnArray = ['是', '否'];
						mui.confirm('当前版本是:' + vername_local + ',  最新版本是:' + verName + ',  是否立即更新?', '发现最新版本', btnArray, function(z) {
							if(z.index == 0) {
								console.log('确定');
								installApk(BASEINFO.maxsvc + appInfo.version_apk);
							} else {
								console.log('不确定');
								return;
							}
						});
					}
				});
			});
		}
	});
}

2.其中需要用到application.js中声明的函数

在这里插入图片描述

3.application.js中的函数

var BASEINFO={
    //接口url
	maxsvc:"http://*.*.*.*:port/appUpdate",	
	maxbiz:"http://*.*.*.*:port/maxbiz",
	download:"http://*.*.*.*:port/whatsup/releaseapk.jsp"
}

function getWinWH() {
	var temp = {};
	var winWidth = "0";
	var winHeight = "0";
	if(window.innerWidth) {
		winWidth = window.innerWidth;
	} else if((document.body) && (document.body.clientWidth)) {
		winWidth = document.body.clientWidth;
	}
	if(window.innerHeight) {
		winHeight = window.innerHeight;
	} else if((document.body) && (document.body.clientHeight)) {
		winHeight = document.body.clientHeight;
	}
	if(document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
		winHeight = document.documentElement.clientHeight;
		winWidth = document.documentElement.clientWidth;
	}
	temp.winWidth = winWidth;
	temp.winHeight = winHeight;

	return temp;
}

function getAppInfo(appname) {
	var prefix = "";
	var path = "";
	var name = "";
	//	MaxUA
	if(appname == "mua") {
		path = "com.maxnerva.maxua";
		prefix = "";
		name = path;
	}
	//	异常停线通知(L5)
	if(appname == "men") {
		path = "com.newpc.b2b.";
		prefix = "asm_";
		name = path + prefix + appname;
	}
	//	E点名(L5)
	if(appname == "mrc") {
		path = "com.newpc.b2b.";
		prefix = "asm_";
		name = path + prefix + appname;
	}
	//	组装生产日报表(L5)
	if(appname == "pdr") {
		path = "com.newpc.b2b.";
		prefix = "asm_";
		name = path + prefix + appname;
	}
	//	仓库进料转仓(L6)
	if(appname == "mgr") {
		path = "com.foxconn.";
		prefix = "";
		name = path + prefix + appname;
	}
	//	发料单查询(L6)
	if(appname == "mgi") {
		path = "com.foxconn.max.activity";
		prefix = "";
		name = path;
	}
	//	仓库分批发料(L5)
	if(appname == "mso") {
		path = "com.newpc.b2b.";
		prefix = "asm_";
		name = path + prefix + appname;
	}
	//	上料表查询(L6)
	if(appname == "mgf") {
		path = "com.newpc.b2b.";
		prefix = "asm_";
		name = path + prefix + appname;
	}
	//	IQC进料检验(L6)
	if(appname == "mqi") {
		path = "com.foxconn.iqc";
		prefix = "";
		name = path;
	}
	//	流程卡(L5)
	if(appname == "wfc") {
		path = "com.mts.";
		prefix = "";
		name = path + prefix + appname;
	}
	
	//	mqi_v
	if(appname == "mqi_v") {
		path = "com.foxconn.";
		prefix = "";
		name = path + prefix + appname;
	}

	var appInfo = {};
	appInfo.scheme = "open";
	appInfo.host = name;
	appInfo.package = name;
	appInfo.version_json = "/resource/download/" + appname + ".json";
	appInfo.version_apk = "/resource/download/" + appname + ".apk";
	appInfo.version_desc = "/resource/download/" + appname + ".desc";
	return appInfo;
}

function installApk(url) {
	var dtask = plus.downloader.createDownload(url, {}, function(d, status) {
		if(status == 200) {
			plus.nativeUI.toast("正在准备环境,请稍后!");
			sleep(1000);
			var path = d.filename;
			console.log(d.filename);
			plus.runtime.install(path);
		} else {
			alert('Download failed:' + status);
		}
	});
	dtask.start();
}

function sleep(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while(true) {
		now = new Date();
		if(now.getTime() > exitTime)
			return;
	}
}

function getAppVersion(packagename) {
	var versionJson = {};
	var main = plus.android.runtimeMainActivity();
	var pm = main.getPackageManager();
	var PackageManager = plus.android.importClass(pm);
	var pi = pm.getPackageInfo(packagename, 0);
	var PackageInfo = plus.android.importClass(pi);
	var vercode_local = plus.android.getAttribute(pi, "versionCode");
	var vername_local = plus.android.getAttribute(pi, "versionName");
	versionJson.vercode_local = vercode_local;
	versionJson.vername_local = vername_local;
	return versionJson;
}

function jumpAndroid(appname) {
	var appInfo = getAppInfo(appname);
	//
	console.log("appInfo  "+appInfo);
	
	var url = appInfo.scheme + "://" + appInfo.host +
		"?BUNDLE_CAMP=" + localStorage.getItem("musercamp") +
		"&BUNDLE_USERNAME=" + localStorage.getItem("musername") +
		"&BUNDLE_USERPASSWRD=" + localStorage.getItem("mpassword");
	//
	console.log("appInfo  "+appInfo);	
	
	try {
		if(plus.os.name == "Android") {
			if(plus.runtime.isApplicationExist({
					pname: appInfo.host,
					action: appInfo.scheme + '://'
				})) {
				var versionJosn = getAppVersion(appInfo.package);
				var vercode_local = versionJosn.vercode_local;
				var vername_local = versionJosn.vername_local;
				mui.getJSON(BASEINFO.maxsvc + appInfo.version_json, null, function(data) {
					var verCode = data.verCode;
					var verName = data.verName;
					if(vercode_local == verCode) {
						location.href = url;
					} else {
						var btnArray = ['是', '否'];
						mui.confirm('当前版本是:' + vername_local + ',  最新版本是:' + verName + ',  是否立即更新?', '发现最新版本', btnArray, function(z) {
							if(z.index == 0) {
								installApk(BASEINFO.maxsvc + appInfo.version_apk);
							} else {
								location.href = url;
							}
						});
					}
				});
			} else {
				var btnArray = ['是', '否'];
				mui.confirm('应用程式未安装,  是否立即安装?', '应用程式安装确认', btnArray, function(z) {
					if(z.index == 0) {
						installApk(BASEINFO.maxsvc + appInfo.version_apk);
					} else {
						return;
					}
				});
			}
		}
	} catch(e) {
		mui.toast("更新失败  "+e.toString());
	}
}


function myAjax(url, type, input, timeout, success, error) {
	var xhr = new plus.net.XMLHttpRequest();
	if(timeout && timeout > 0) xhr.timeout = timeout;
	xhr.onreadystatechange = function() {
		switch(xhr.readyState) {
			case 0:
				console.log("xhr请求已初始化");
				break;
			case 1:
				console.log("xhr请求已打开");
				break;
			case 2:
				console.log("xhr请求已发送");
				break;
			case 3:
				console.log("xhr请求已响应");
				break;
			case 4:
				if(xhr.status == 200) {
					success(eval('('+xhr.responseText + ')'));
				} else {
					error(xhr.readyState, xhr);
				}
				break;
			default:
				break;
		}
	}
	if(input) {
		if(type == 'post' || type == 'get') {
			xhr.open(type || "GET", url);
			xhr.send(JSON.stringify(input));
		} else {
			throw new Error("type is undefined !")
		}
	} else {
		if(type != 'post' && type != 'get') {
			throw new Error("type is undefined !")
		}
		xhr.open(type || "GET", url);
		xhr.send();
	}
}

function isSysAdmin(groups) {
	var result = false;
	for(var i = 0; i < groups.length; i++) {
		var group = groups[i];
		if(group.groupcode.toUpperCase() == "SYSADMIN") {
			result = true;
			break;
		}
	}
	return result;
}

function isReadonly() {
	var result = false;
	var muserStr=localStorage.getItem("muser");
	var muserObj=eval('(' + muserStr + ')');
	var groups=muserObj.group;
	if(groups && groups.length>0 && groups[0].groupcode.toUpperCase().indexOf("_READ")>0) result = true;
	return result;
}

function getLongUsername(){
	var muserStr=localStorage.getItem("muser");
	var muserObj=eval('(' + muserStr + ')');
	var muser=muserObj.user;
	return muser.username+"("+muser.lastname+")";
}

//其他方法检查版本
function svn(t) {   
    var xhr_svn = new plus.net.XMLHttpRequest();   
    xhr_svn.onreadystatechange = function() {   
        if (xhr_svn.readyState == 4) {   
            if (xhr_svn.status == 200) {   
                var res = JSON.parse(xhr_svn.responseText);   
                if (res.state == 'yes') {   
                    if (res.mark != t) {   
                        var upr;   
                        plus.nativeUI.confirm( "有新版本发布了,是否件更新?", function(e){   
                            upr=(e.index==0)?"Y":"N";   
                            console.log(upr);   
                            if(upr=="Y"){   
                            var wt = plus.nativeUI.showWaiting('下载更新中,请勿关闭');   
                            var url = res.url; // 下载文件地址   
                            var dtask = plus.downloader.createDownload(url, {}, function(d, status) {   
                                if (status == 200) { // 下载成功   
                                    var path = d.filename;   
                                    console.log(d.filename);   
                                    plus.runtime.install(path);   
                                } else { //下载失败   
                                    alert("Download failed: " + status);   
                                }   
                            });   
                            dtask.start();   
                            }else{   
                                   
                            }   
                        }, "XXX系统", ["确认","取消"] );   
                    } else {   
                        console.log('最新');   
                    }   
                }   
            } else {   
                plus.nativeUI.toast( "网络连接错误!");   
            }   
        }   
    }   
    xhr_svn.open("GET", "http:/XXX/APPobject/imes/update.json");//这里的地址是上面json文件的地址   
    xhr_svn.send();      
}

4.服务器端添加配置信息

1.主要添加json(新版本信息),apk(新版本安装包),desc(描述文件)
在这里插入图片描述

posted @ 2019-10-09 15:20  gqzdev  阅读(4426)  评论(0编辑  收藏  举报