app-update.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. export function downloadApkWithJsonPost(apiUrl, requestData) {
  2. fetch(apiUrl, {
  3. method: "POST",
  4. headers: {
  5. "Content-Type": "application/json",
  6. },
  7. body: JSON.stringify(requestData),
  8. })
  9. .then((response) => {
  10. if (!response.ok) throw new Error("下载失败");
  11. return response.blob(); // 获取二进制 APK 文件
  12. })
  13. .then((blob) => {
  14. saveBlobToFile(blob); // 保存到本地
  15. })
  16. .catch((err) => {
  17. plus.nativeUI.alert("更新失败:" + err.message);
  18. });
  19. }
  20. function saveBlobToFile(blob) {
  21. const apkPath = "_doc/update/app.apk";
  22. plus.io.resolveLocalFileSystemURL("_doc/", function (dirEntry) {
  23. dirEntry.getDirectory("update", { create: true }, function (updateDir) {
  24. updateDir.getFile("app.apk", { create: true }, function (fileEntry) {
  25. fileEntry.createWriter(function (writer) {
  26. writer.onwrite = function () {
  27. console.log("文件保存成功");
  28. installApk(fileEntry.toLocalURL());
  29. };
  30. writer.onerror = function (e) {
  31. plus.nativeUI.alert("保存文件失败:" + e.message);
  32. };
  33. writer.write(blob);
  34. });
  35. });
  36. });
  37. });
  38. }
  39. function installApk(filepath) {
  40. plus.runtime.install(
  41. filepath,
  42. {
  43. force: true,
  44. },
  45. function () {
  46. plus.nativeUI.alert("更新完成,应用即将重启", function () {
  47. plus.runtime.restart();
  48. });
  49. },
  50. function (e) {
  51. plus.nativeUI.alert("安装失败:" + JSON.stringify(e));
  52. }
  53. );
  54. }