1.安裝cordova-plugin-file (https://ionicframework.com/docs/native/file)
ionic cordova plugin add cordova-plugin-file
npm install @ionic-native/file
該插件實(shí)現(xiàn)了File API锹漱,允許對(duì)設(shè)備上存在的文件進(jìn)行讀/寫訪問捡絮。
File類實(shí)現(xiàn)靜態(tài)便利功能月腋,以訪問文件和目錄夯到。
2.安裝cordova-plugin-file-transfer (https://ionicframework.com/docs/native/file-transfer)
ionic cordova plugin add cordova-plugin-file-transfer
npm install @ionic-native/file-transfer
該插件可上傳和下載文件边翁。
3.安裝cordova-plugin-file-opener2 (https://ionicframework.com/docs/native/file-opener)
ionic cordova plugin add cordova-plugin-file-opener2
npm install @ionic-native/file-opener
該插件將使用其默認(rèn)應(yīng)用程序在您的設(shè)備文件系統(tǒng)上打開一個(gè)文件。
相關(guān)插件安裝完成之后.......接下來實(shí)現(xiàn)app自動(dòng)更新下載
代碼如下:
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(e})
.catch(e => {console.log(e});
}, (error) => {console.log(error)});
const progressNum = document.getElementById('progressnum');
fileTransfer.onProgress((event) => {
let num = Math.ceil(event.loaded / event.total * 100); //轉(zhuǎn)化成1-100的進(jìn)度
if (num === 100) {
progressNum.innerHTML = '下載完成';
} else {
progressNum.innerHTML = '下載進(jìn)度:' + num + '%';
}
});
注: (1)let saveurl = this.file.externalDataDirectory ? this.file.externalDataDirectory : this.file.dataDirectory; //因?yàn)橐恍┦謾C(jī)this.file.externalDataDirectory是找不到的抚恒,因此需要判斷下
(2)this.targetUrl //為你線上鏈接的apk
(3)fileTransfer.onProgress((event) => {
let num = Math.ceil(event.loaded / event.total * 100); //轉(zhuǎn)化成1-100的進(jìn)度
if (num === 100) {
progressNum.innerHTML = '下載完成';
} else {
progressNum.innerHTML = '下載進(jìn)度:' + num + '%';
}
}); //計(jì)算當(dāng)前apk的下載進(jìn)度
Cordova打包項(xiàng)目在Android8.0及以上版本更新下載后不能打開APP問題。Android APK安裝限制 打開APK文件進(jìn)行安裝時(shí)蛤奢,以下限制適用: 在Android 8+上,您的應(yīng)用程序必須具有ACTION_INSTALL_PACKAGE權(quán)限让腹。
你可以將它添加到應(yīng)用程序config.xml文件中:
<platform name="android">
<config-file parent="/manifest" target="AndroidManifest.xml" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
</config-file>
</platform>