之前在写自动安装APP这块碰到了不少问题,今天终于有时间来总结下
1.插件安装如下:
(1)文件插件
ionic cordova plugin add cordova-plugin-file
npm install @ionic-native/file
(2)文件传输插件
ionic cordova plugin add cordova-plugin-file-transfer
npm install @ionic-native/file-transfer
(3)文件打开插件
ionic cordova plugin add cordova-plugin-file-opener2
npm install @ionic-native/file-opener
2.代码流程如下
(1)从后台获取APP链接
let that = this;
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': localStorage.getItem('Authorization') }),
withCredentials: true
}
this.appVersion.getVersionNumber().then(ver => {
this.http.post(this.api +"', { 'appid': "", 'version_code': "" }, httpOptions).subscribe(
async (response: any) => {
that.targetUrl = response.data.app_version.download_url;
that.showAlert();
},
err => {
console.log(err)
}
)
})
(2)把APP安装到手机指定路径下并打开APP安装在手机上
downloadApp() {
let that = this;
const fileTransfer: FileTransferObject = this.transfer.create();
let saveurl = this.file.externalDataDirectory ? this.file.externalDataDirectory : this.file.dataDirectory;
let apk = saveurl + 'download/' + 'ezhear.apk';
fileTransfer.download(this.targetUrl, apk).then((entry) => {
this.fileOpener.open(apk, "application/vnd.android.package-archive")
.then((e) => {
console.log('File is opened', e)
})
.catch(e => {
console.log('Error openening file', e)
});
}, (error) => {
alert(JSON.stringify(error));
});
var progressNum = document.getElementById('progressnum');
/**下载进度条*/
fileTransfer.onProgress((event) => {
let num = Math.ceil(event.loaded / event.total * 100); //转化成1-100的进度
if (num === 100) {
progressNum.innerHTML = '下载完成';
} else {
progressNum.innerHTML = '下载进度:' + num + '%';
}
});
}
插件下载链接地址如下:
(1) https://ionicframework.com/docs/native/file
(2) https://ionicframework.com/docs/native/file-opener
(3) https://ionicframework.com/docs/native/file-transfer