1.安装插件
$ ionic plugin add cordova-plugin-file
$ npm install --save @ionic-native/file
$ ionic plugin add cordova-plugin-file-transfer
$ npm install --save @ionic-native/transfer
$ ionic plugin add cordova-plugin-file-opener2
$ npm install --save @ionic-native/file-opener
$ ionic plugin add cordova-plugin-app-version
$ npm install --save @ionic-native/app-version
$ ionic plugin add cordova-plugin-app-update
$ npm install --save @ionic-native/app-update
2. app.module.ts声明
import {
File }
from
'@ionic-native/file';
import {
FileOpener }
from
'@ionic-native/file-opener';
import {
Transfer }
from
'@ionic-native/transfer';
import {
AppVersion }
from
'@ionic-native/app-version';
providers: [
StatusBar,
SplashScreen,
{
provide:
ErrorHandler,
useClass:
IonicErrorHandler},
AppVersion,
File,
FileOpener,
Transfer
]
3.实现
import {
File }
from
'@ionic-native/file';
import {
FileOpener }
from
'@ionic-native/file-opener';
import {
Transfer,
TransferObject }
from
'@ionic-native/transfer';
private
fileTransfer:
TransferObject;
constructor(
public
navCtrl:
NavController,
public
navParams:
NavParams,
private
alertCtrl:
AlertController,
private
appVersion:
AppVersion,
private
loadingCtrl:
LoadingController,
private
file:
File,
private
fileOpener:
FileOpener,
private
transfer:
Transfer) {
this.
fileTransfer =
this.
transfer.
create();
}
// 版本更新
openUpdateVersion(){
if(
this.
appVersionNumber ==
AppConfig.
APP_VERSION_NUM){
this.
toastCtrl.
create({
message:
'当前已是最新版本!',
duration:
2000,
position:
'top'
}).
present();
return;
}
let
alert =
this.
alertCtrl.
create({
title:
'版本更新',
message:
'发现最新版本为'+
AppConfig.
APP_VERSION_NUM+
', 是否更新?',
buttons: [
{
text:
'取消',
role:
'cancel',
handler: ()
=> {
console.
log(
'取消');
}
},
{
text:
'更新',
handler: ()
=> {
console.
log(
'更新');
this.
loadAPP();
}
}
]
});
alert.
present();
}
// 下载app
private
loadAPP(){
let
loading =
this.
loadingCtrl.
create({
spinner:
'ios',
content:
'安装包正在下载...',
dismissOnPageChange:
false
});
loading.
present();
// 下载
this.
fileTransfer.
download(
AppConfig.
IP_QDP+
"upload/file/test.apk",
"file:///storage/sdcard0/Download/qdg.apk").
then((
entry)
=> {
loading.
dismiss();
this.
fileOpener.
open(
"file:///storage/sdcard0/Download/qdg.apk",
'application/vnd.android.package-archive').
then(()
=>{});
}, (
error)
=> {
// handle error
console.
log(
'download error');
loading.
dismiss();
});
// 进度
this.
fileTransfer.
onProgress((
event)
=> {
//进度,这里使用文字显示下载百分比
var
downloadProgress = (
event.
loaded /
event.
total) *
100;
loading.
setContent(
"已经下载:" +
Math.
floor(
downloadProgress) +
"%");
if (
downloadProgress >
99) {
loading.
dismiss();
}
});
}