// 注:下载成功后如果app无法自动安装,提示exposed beyond app through Intent.getData(),需要修改AndroidManifest.xml,可以在platforms/android/app/src/main/AndroidManifest.xml 中找到文件,尽量保持android:targetSdkVersion版本在24以下。
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" />
// 1 安装插件
// 权限
$ ionic cordova plugin add cordova-plugin-android-permissions
$ npm install --save @ionic-native/android-permissions
// 文件管理
$ ionic cordova plugin add cordova-plugin-file
$ npm install --save @ionic-native/file
// 文件上传
$ ionic cordova plugin add cordova-plugin-file-transfer
$ npm install --save @ionic-native/file-transfer
$ ionic cordova plugin add cordova-plugin-file-opener2
$ npm install --save @ionic-native/file-opener
// 版本检测
$ ionic cordova plugin add cordova-plugin-app-version
$ npm install --save @ionic-native/app-version
// 浏览器
$ ionic cordova plugin add cordova-plugin-inappbrowser
$ npm install --save @ionic-native/in-app-browser
//添加插件
//app.module.ts
import { AndroidPermissions } from '@ionic-native/android-permissions';
import { File } from "@ionic-native/file";
import { FileOpener } from "@ionic-native/file-opener";
import { FileTransfer,FileTransferObject } from "@ionic-native/file-transfer";
import { AppVersion } from "@ionic-native/app-version";
import { InAppBrowser} from "@ionic-native/in-app-browser";
import { NativeService } from "../provider/NativeService";
...
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
AndroidPermissions,
File,
AppVersion,
FileOpener,
FileTransfer,
FileTransferObject,
NativeService,
InAppBrowser
]
// 2 应用
// app.component.ts
import { Injectable } from '@angular/core';
import { Platform, AlertController } from 'ionic-angular';
import { AppVersion } from '@ionic-native/app-version';
import { File } from '@ionic-native/file';
import { FileTransfer, FileTransferObject } from "@ionic-native/file-transfer";
import { FileOpener } from '@ionic-native/file-opener';
import { AndroidPermissions } from '@ionic-native/android-permissions';
import { InAppBrowser } from '@ionic-native/in-app-browser';
@Injectable()
export class NativeService {
constructor(private platform: Platform,
private alertCtrl: AlertController,
private transfer: FileTransfer,
private appVersion: AppVersion,
private file: File,
private fileOpener: FileOpener,
private androidPermissions: AndroidPermissions,
private inAppBrowser: InAppBrowser) {
}
//检查权限
permissionsFun(newInfo){
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE).then(
result => {
if (!result.hasPermission){
this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE])
.then(result => {//弹出弹框是否允许
if(result.hasPermission){//点击允许
this.downloadApp(newInfo);
// alert("允许使用LOCATION权限");
}else{//点击拒绝
// alert("拒绝使用LOCATION权限");
this.platform.exitApp();//退出APP
}
});
}else{
this.downloadApp(newInfo);
// alert("已允许位置权限" + result.hasPermission);
}
},
err => {
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION)
}
);
}
/**
* 检查app是否需要升级
*/
detectionUpgrade(newInfo) {
//这里连接后台获取app最新版本号,然后与当前app版本号(this.getVersionNumber())对比
//版本号不一样就需要申请,不需要升级就return
this.alertCtrl.create({
title: '升级',
subTitle: '发现新版本,是否立即升级?',
enableBackdropDismiss: false,
buttons: [{ text: '取消',
handler: () => {
this.platform.exitApp();
} },
{
text: '确定',
handler: () => {
this.permissionsFun(newInfo);
}
}
]
}).present();
}
/**
* 下载安装app
*/
downloadApp(newInfo) {
if (this.isAndroid()) {
let alertBut = this.alertCtrl.create({
title: '下载进度:0%',
enableBackdropDismiss: false,
// buttons: ['后台下载']
});
alertBut.present();
// alert(JSON.stringify(newInfo));
const fileTransfer: FileTransferObject = this.transfer.create();
const apk = this.file.externalRootDirectory + newInfo.FILE_NAME; //apk保存的目录
const url = newInfo.URL + newInfo.FILE_NAME;
fileTransfer.download(encodeURI(url), apk).then((res: any) => {
this.fileOpener.open(apk, 'application/vnd.android.package-archive').then((value) => {
// alert(JSON.stringify(value));
}).catch(err => {
// alert(JSON.stringify(err));
});
}).catch(error => {
// alert(JSON.stringify(error));
});
fileTransfer.onProgress((event: ProgressEvent) => {
console.log(event);
let num = Math.floor(event.loaded / event.total * 100);
if (num === 100) {
alertBut.dismiss();
} else {
let title = document.getElementsByClassName('alert-title')[0];
title && (title.innerHTML = '下载进度:' + num + '%');
}
});
}
// if (this.isIos()) {
// this.openUrlByBrowser("这里边填写下载iOS地址");
// }
}
/**
* 通过浏览器打开url
*/
openUrlByBrowser(url: string): void {
this.inAppBrowser.create(url, '_system');
}
/**
* 是否真机环境
* @return {boolean}
*/
isMobile(): boolean {
return this.platform.is('mobile') && !this.platform.is('mobileweb');
}
/**
* 是否android真机环境
* @return {boolean}
*/
isAndroid(): boolean {
return this.isMobile() && this.platform.is('android');
}
/**
* 是否ios真机环境
* @return {boolean}
*/
isIos(): boolean {
return this.isMobile() && (this.platform.is('ios') || this.platform.is('ipad') || this.platform.is('iphone'));
}
/**
* 获得app版本号,如0.01
* @description 对应/config.xml中version的值
* @returns {Promise<string>}
*/
versionInfo: string;
getVersionNumber(newInfo): Promise<string> {
return new Promise((resolve) => {
this.appVersion.getVersionNumber().then((value: string) => {
resolve(value);
console.log(value);
if (newInfo.VEISION !== value) {
this.detectionUpgrade(newInfo);
} else {
this.versionInfo = '已是最新版本';
}
}).catch(err => {
console.log('getVersionNumber:' + err);
});
});
}
}
getAppVersion() {
let headers = new HttpHeaders(
{
'HH-Authorization': localStorage.TOKEN,
'Content-Type': 'application/x-www-form-urlencoded',
})
return this.http.post(this.url + 'account/getAppVersion', '', {headers})
.subscribe(
(res: any) => {
console.log(res);
if (!res.IsErr) {
this.nativeService.getVersionNumber(res.Data);//检查app是否升级
} else {
this.GlobalFun.popToastView(res.Msg);
}
}), (error: any) => {
console.log(error);
}
}
网友评论