import { HttpClient } from '@angular/common/http'; import { EventEmitter, Injectable } from '@angular/core'; import { AppVersion } from '@ionic-native/app-version/ngx'; import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx'; import { FileOpener } from '@ionic-native/file-opener/ngx'; import { File } from '@ionic-native/file/ngx'; @Injectable({ providedIn: 'root' }) export class UpdateService { // 获取最新版本地址 serviceVersionInfoUrl = 'http://192.168.137.1/'; serviceVersionInfo: { elements: { versionName: string, outputFile: string }[] } = null; onDownProgress = new EventEmitter(); constructor( private appVersion: AppVersion, private file: File, private transfer: FileTransfer, private fileOpener: FileOpener, private http: HttpClient) { this.onDownProgress.subscribe(p => { console.log(`AppDownProgress: ${p}%`); }); } getAppVersion(): Promise { return this.appVersion.getVersionNumber(); } getAppName(): Promise { return this.appVersion.getAppName(); } loadVersionInfo(): Promise<{ elements: { versionName: string, outputFile: string }[] }> { return new Promise((resolve, reject) => { this.http.get(this.serviceVersionInfoUrl + 'output-metadata.json').subscribe(serviceVersion => { console.log('serv: ' + JSON.stringify(serviceVersion)); resolve(serviceVersion as any); }, error => { console.log(JSON.stringify(error)); }) }); } async getServiceVersion(): Promise { if (!this.serviceVersionInfo) { this.serviceVersionInfo = await this.loadVersionInfo(); } return this.serviceVersionInfo.elements[0].versionName; } async getServiceAppName(): Promise { if (!this.serviceVersionInfo) { this.serviceVersionInfo = await this.loadVersionInfo(); } return this.serviceVersionInfo.elements[0].outputFile; } async isNewVersion(): Promise { const appVersion = await this.getAppVersion(); console.log('appVersion: ' + appVersion); const serviceVersion = await this.getServiceVersion(); console.log('serviceVersion: ' + serviceVersion); return appVersion !== serviceVersion; } async updateApp() { if (await this.isNewVersion()) { await this.downApp(); } } async downApp() { const fileTransfer: FileTransferObject = this.transfer.create(); const serviceAppName = await this.getServiceAppName(); const apk = this.file.dataDirectory + serviceAppName; fileTransfer.download(this.serviceVersionInfoUrl + serviceAppName, apk).then((entry) => { this.fileOpener.open(apk, "application/vnd.android.package-archive") .then((e) => console.log(e)) .catch(e => console.log(e)); console.log('download complete: '); }, (error) => { // handle error console.log('download error :' + JSON.stringify(error)) }); this.onDownProgress.emit(0); fileTransfer.onProgress((event) => { let num = Math.ceil(event.loaded / event.total * 100); //转化成1-100的进度 this.onDownProgress.emit(num); }); } }