最近在使用HBuilder的MUI做一个H5的APP,碰到一个检测升级的问题,晚上熬夜码代码,终于研究出来了;简单做一个记录,方便下一次使用。
说明:需求是启动app时,自动检测更新,提示升级,并下载安装。
代码
- plus.runtime.getProperty(plus.runtime.appid,function(inf) {
- ver = inf.version;
- console.log('手机版本ver:' + ver);
- var ua = navigator.userAgent.toLowerCase();
- console.log('手机版本型号:' + ua);
- var url = SERVER_HOST + MODULE_UpdateApp + '?version=' + ver;
- var client;
- console.log('手机版本型号:' + mui.os);
- mui.ajax(url, {
- type: 'get',
- //HTTP请求类型
- timeout: 10000,
- //超时时间设置为10秒;
- //async: false,
- dataType: "json",
- headers: {
- 'Content-Type': 'application/json'
- },
- success: function(data) {
- if (data.status == 0) return;
- if (data.status == 1) {
- var btn = ["确定升级", "取消"];
- mui.confirm('更新内容:\n' + data.note, '软件升级提醒', btn,
- function(z) {
- if (z.index == 0) {
- var apkUrl = data.url;
- plus.nativeUI.showWaiting("下载更新");
- plus.downloader.createDownload(apkUrl, {
- filename: "_doc/update/"
- },
- function(download, status) {
- if (status == 200) {
- mui.toast("下载更新成功:" + status);
- plus.runtime.install(download.filename);
- } else {
- mui.toast("下载更新成功:" + status);
- plus.nativeUI.toast("下载更新失败!");
- }
- plus.nativeUI.closeWaiting();
- }).start();
- } else {
- console.log('不确定');
- return;
- }
- });
- }
- },
- error: function(xhr, type, errorThrown) {
- //异常处理;
- mui.alert("网络异常" + type);
- console.log(type);
- }
- });
- });
将这个代码放置在APP启动页面入口的 $.plusReady(function() {});内,最好就在这个下面。这个函数相当于Js的页面加载完成后执行。
接口
- /// <summary>
- /// 版本更新
- /// </summary>
- /// <param name="obj"></param>
- /// <returns></returns>
- [Route("UpdateApp")]
- [HttpGet]
- public dynamic UpdateApp(string version)
- {
- try
- {
- if (version == null || version == "")
- return new { status = 0 };
- if (version != "0.1.191114")//最新版本号及relase notes可以存储在数据库或文件中
- {
- return new { status = 1, title = "应用更新", note = "1.修复发现的bug;\n2.增加在线更新;", url = "apk下载地址" };
- }
- return new { status = 0 };
- }
- catch (Exception ex)
- {
- //输出错误日志
- return new { status = 0 };
- }
- }
该接口采用ASP.NET MVC中的WebAPI,仅供参考。
继续阅读

微信公众号
博客微信公众号,欢迎关注。
2020年2月28日 下午12:25 2F
我在用pc版
2020年2月28日 下午12:27 B1
@ 小王先森 我这个只是HBuilder中提供的MUI框架做app的一个自动升级APP的代码展示。
2019年11月14日 下午10:48 1F
内容不错。域名很随意
2019年11月18日 下午5:54 B1
@ 鹅鹅鹅 域名很好啊,内容确实不错