不废话,直接上代码
首先安装四个必备的插件:
cordova plugin add cordova-plugin-app-version //获取APP版本
cordova plugin add cordova-plugin-file //文件管理
cordova plugin add cordova-plugin-file-transfer //文件传输
cordova plugin add cordova-plugin-file-opener2 //文件打开
运行上面给出的命令安装好这四个插件,创建一个Porvider用来写更新代码
ionic g provider UpdateAPP
详细更新代码
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/operator/map'; import { Global } from '../providers/global/global'; //这是我个人封装的一个全局类,不必理会 import { LoadingController, AlertController } from 'ionic-angular'; //引入加载框和更新提示框 import { AppVersion, Transfer, FileOpener } from 'ionic-native' //引入更新需要的几个插件 @Injectable() export class UpdateappProvider { private appUrl="http://xxx/xxx.apk"; //可以从服务端获取更新APP的路径 constructor(public http: Http, public g: Global, private loadingCtrl: LoadingController, private alertCtrl: AlertController) { } //检查版本更新 checkUpdate() { let execName = 'xxx'; let param = { APPNAME: 'xxx', }; //查询当前服务器的APP版本号与当前版本号进行对比 //g.Post是我自己封装一个数据查询类 请自行替换自己的 this.g.Post(execName, param, '', true, true).then((data: Array<any>) => { console.log(data); AppVersion.getVersionNumber().then((version) => { console.log(version); if (data[0].VERSION != version) { // this.appUrl=data[0].APPURL; //可以从服务端获取更新APP的路径 let updateAlert = this.alertCtrl.create({ title: '提示', message: '发现新版本,是否立即更新?', buttons: [{ text: '取消' }, { text: '确定', handler: data => { this.upgradeApp(); } } ] }); updateAlert.present(); } }); }); } upgradeApp() { const fileTransfer = new Transfer(); let uploading = this.loadingCtrl.create({ content: "安装包正在下载...", dismissOnPageChange: false }); var targetPath = "/sdcard/Download/CaiLaoBan.apk"; //APP下载存放的路径,可以使用cordova file插件进行相关配置 // var options = {}; uploading.present(); fileTransfer.onProgress((event) => { //进度,这里使用文字显示下载百分比 // setTimeout(() => { var downloadProgress = (event.loaded / event.total) * 100; uploading.setContent("已经下载:" + Math.floor(downloadProgress) + "%"); if (downloadProgress > 99) { uploading.dismiss(); } // }, 100); /* setTimeout(() => { uploading.dismiss(); }, 10000);*/ }); //url为服务端地址 //targetPath为设备上的地址 fileTransfer.download(this.appUrl, targetPath, true).then( (result) => { uploading.dismiss(); FileOpener.open(targetPath, 'application/vnd.android.package-archive').then( () => { }); } ); } }
在app.component.ts的构造方法里调用升级代码
//检查应用是否需要更新 updateapp.checkUpdate();
如有问题,欢迎讨论(^o^)/~
效果:
转载请注明出处:http://www.cnblogs.com/super-cj/p/6279009.html