ionic2项目需要实力在线更新功能,ios比较简单,跳转到app store的链接地址了
android就需要花一些气力了,上代码
需要先安装一些插件
cordova-plugin-file,
cordova.plugins.fileOpener2,
cordova-plugin-file-transfer
appHttp这个自已封装的http请求对象,做拦截用的,可忽略,不在这次说明的内容内
appConfig是自已封装的全局参数对象,主要放平台,版本,服务端请求地址等,可忽略
//检查更新新版本 checkVersion(){ this.appHttp.get("http://url").then(data=>{ if(data.code=='0'){ this.alertCtrl.create({ message: ''+data.message+'', buttons: [{ text: '残忍放弃', role: 'cancel' },{ text: '立即下载', handler: () => { this.updateNewApp(data); } } ] }).present(); }else{ this.loadingCtrl.create({spinner: 'hide',content:'已经是最新版本!',duration:2000}).present(); } }).catch(data=>{ this.loadingCtrl.create({spinner: 'hide',content:'检查版本时发生网络异常,请稍后再试!',duration:2000}).present(); }) }
updateNewApp = function(data){ if(this.appConfig.platform == 'ios'){ window.open(data.result); }else { let cordova = (<any>window).cordova; if ((<any>window).FileTransfer) { let fileTransfer = new (<any>window).FileTransfer(); let fileURL = cordova.file.externalDataDirectory + "android.apk"; if (!cordova.file.externalDataDirectory) { this.loadingCtrl.create({spinner: 'hide', content: '无法安装,请尝试从应用市场安装更新!', duration: 2000}).present(); return; } let loading = this.loadingCtrl.create({ content: '下载进度:0%', dismissOnPageChange: false }); loading.present(); let no:number = 1; fileTransfer.onprogress = function (progressEvent) { if (progressEvent.lengthComputable) { no = progressEvent.loaded / progressEvent.total * 100; } }; let timer = setInterval(() => { loading.setContent("下载进度:" + Math.floor(no) + "%"); if (no >= 99) { clearInterval(timer); } }, 300); fileTransfer.download(encodeURI(data.result), fileURL, function (r) { if(timer)clearInterval(timer); loading.dismiss(); cordova.plugins.fileOpener2.open(r.toURL(), "application/vnd.android.package-archive"); }, function () { if(timer)clearInterval(timer); loading.dismiss(); this.loadingCtrl.create({spinner: 'hide',content: '出错了,请尝试从应用市场安装更新!', duration: 2000}).present(); }); } } }
关键代码在这里:
let no:number = 1; fileTransfer.onprogress = function (progressEvent) { if (progressEvent.lengthComputable) { no = progressEvent.loaded / progressEvent.total * 100; } }; let timer = setInterval(() => { loading.setContent("下载进度:" + Math.floor(no) + "%"); if (no >= 99) { clearInterval(timer); } }, 300);后面那个定时器里的代码理论上可以写到上面,但那样百分比分一直不动,达不到效果
我的认为是js阻塞了线程,前端内容无法宣染,加了定时器后效果不错