versionUpdate.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. export function useVersionUpdate() {
  2. function getVersion() {
  3. // 获取当前应用版本
  4. plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
  5. // 请求服务器,获取最新版本信息 (示例)
  6. uni.request({
  7. url: 'https://your-api-domain.com/check-update',
  8. method: 'GET',
  9. data: {
  10. appid: plus.runtime.appid,
  11. version: widgetInfo.version,
  12. versionCode: widgetInfo.versionCode
  13. },
  14. success: (res) => {
  15. if (res.statusCode === 200) {
  16. const serverData = res.data;
  17. // 对比版本号[2](@ref)
  18. if (compareVersion(serverData.version, widgetInfo.version) > 0) {
  19. // 发现新版本,提示用户更新
  20. this.showUpdateDialog(serverData);
  21. }
  22. }
  23. }
  24. });
  25. });
  26. }
  27. function compareVersion(v1, v2) {
  28. v1 = v1.split('.');
  29. v2 = v2.split('.');
  30. const len = Math.max(v1.length, v2.length);
  31. while (v1.length < len) v1.push('0');
  32. while (v2.length < len) v2.push('0');
  33. for (let i = 0; i < len; i++) {
  34. const num1 = parseInt(v1[i]);
  35. const num2 = parseInt(v2[i]);
  36. if (num1 > num2) return 1;
  37. if (num1 < num2) return -1;
  38. }
  39. return 0;
  40. }
  41. // 提示用户更新并下载安装包[4](@ref)
  42. function showUpdateDialog(updateData) {
  43. uni.showModal({
  44. title: '发现新版本',
  45. showCancel: false,
  46. content: updateData.description || '有新的版本可用,请更新体验更多功能',
  47. confirmText: '立即更新',
  48. success: (res) => {
  49. if (res.confirm) {
  50. // 下载APK文件[4](@ref)
  51. plus.runtime.openURL(updateData.url); // 调用系统浏览器下载
  52. // 或使用下载管理器直接下载安装[5](@ref)
  53. }
  54. }
  55. });
  56. }
  57. return {
  58. getVersion,
  59. compareVersion,
  60. showUpdateDialog
  61. }
  62. }