1.安裝
cordova plugin add cordova-plugin-file-transfer
cordova plugin add cordova-plugin-file-opener2
2.下載.apk
var ft = new FileTransfer();
//監聽下載進度
ft.onprogress = function (e) {
if (e.lengthComputable) {
var progress = e.loaded / e.total * 100;
$("#progress").css({ "width": progress + "%" });
$("#progress").html(progress + "%");
}
}
ft.download(zyd.openApp._downloadUrl, filePath, function (entry) {
console.log('下載成功');
console.info(JSON.stringify(entry));
console.log('文件位置:' + entry.toURL());
// 打開apk安裝包
cordova.plugins.fileOpener2.open(
entry.toURL(), 'application/vnd.android.package-archive', {
error: function (e) {
alert('失敗status:' + JSON.stringify(e) + " 路徑:" + entry.toURL())
},
success: function () {
alert("安裝完成後請重新打開。");
}
});
}, function (err) {
console.log("下載失敗!");
console.info(JSON.stringify(err));
}, null, {});
- vue 使用
downloadApk(url) {
const fileTransfer = new FileTransfer()
const uri = encodeURI(url)
const fileURL = 'cdvfile://localhost/temporary/update.apk'
fileTransfer.onprogress = (e) => {
if (e.lengthComputable) {
this.update.show = true
let progress = Math.ceil(e.loaded / e.total * 100)
if (progress < 100) {
this.update.progress = progress;
} else {
this.update.progress = 100;
this.update.show = false
}
}
}
fileTransfer.download(uri, fileURL,
function (entry) {
cordova.plugins.fileOpener2.open(
entry.toURL(), 'application/vnd.android.package-archive', {
error: function (e) {
this.$tip("fail", `打開失敗,文件路徑:${entry.toURL()}`);
},
success: function () { }
}
)
},
function (error) {
this.$tip("fail", "下載失敗");
}
)
}