upgrade.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /**
  2. * @description H5+下载App
  3. * @param downloadUrl:App下载链接
  4. * @param progressCallBack:下载进度回调
  5. */
  6. export const downloadApp = (downloadUrl, progressCallBack = () => {}, ) => {
  7. return new Promise((resolve, reject) => {
  8. //创建下载任务
  9. const downloadTask = plus.downloader.createDownload(downloadUrl, {
  10. method: "GET"
  11. }, (task, status) => {
  12. console.log(status,'status')
  13. if (status == 200) { //下载成功
  14. resolve(task.filename)
  15. } else {
  16. reject('fail')
  17. uni.showToast({
  18. title: '下载失败',
  19. duration: 1500,
  20. icon: "none"
  21. });
  22. }
  23. })
  24. //监听下载过程
  25. downloadTask.addEventListener("statechanged", (task, status) => {
  26. switch (task.state) {
  27. case 1: // 开始
  28. break;
  29. case 2: //已连接到服务器
  30. break;
  31. case 3: // 已接收到数据
  32. console.log(task,'task')
  33. let hasProgress = task.totalSize && task.totalSize > 0 //是否能获取到App大小
  34. if (hasProgress) {
  35. let current = parseInt(100 * task.downloadedSize / task.totalSize); //获取下载进度百分比
  36. progressCallBack(current,task.downloadedSize,task.totalSize)
  37. }
  38. break;
  39. case 4: // 下载完成
  40. break;
  41. }
  42. });
  43. //开始执行下载
  44. downloadTask.start();
  45. })
  46. }
  47. /**
  48. * @description H5+安装APP
  49. * @param fileName:app文件名
  50. * @param callBack:安装成功回调
  51. */
  52. export const installApp = (fileName, callBack = () => {}) => {
  53. //注册广播监听app安装情况
  54. onInstallListening(callBack);
  55. //开始安装
  56. plus.runtime.install(plus.io.convertLocalFileSystemURL(fileName), {}, () => {
  57. //成功跳转到安装界面
  58. }, function(error) {
  59. uni.showToast({
  60. title: '安装失败',
  61. duration: 1500,
  62. icon: "none"
  63. });
  64. })
  65. }
  66. /**
  67. * @description 注册广播监听APP是否成功
  68. * @param callBack:安装成功回调函数
  69. */
  70. const onInstallListening = (callBack = () => {}) => {
  71. let mainActivity = plus.android.runtimeMainActivity(); //获取activity
  72. //生成广播接收器
  73. let receiver = plus.android.implements('io.dcloud.android.content.BroadcastReceiver', {
  74. onReceive: (context, intent) => { //接收广播回调
  75. plus.android.importClass(intent);
  76. mainActivity.unregisterReceiver(receiver); //取消监听
  77. callBack()
  78. }
  79. });
  80. let IntentFilter = plus.android.importClass('android.content.IntentFilter');
  81. let Intent = plus.android.importClass('android.content.Intent');
  82. let filter = new IntentFilter();
  83. filter.addAction(Intent.ACTION_PACKAGE_ADDED); //监听apk安装
  84. filter.addDataScheme("package");
  85. mainActivity.registerReceiver(receiver, filter); //注册广播
  86. }