文档开发者中心
我的
|

HarmonyOS 6

HarmonyOS 5

【应用内更新】鸿蒙 APP 如何实现应用内自动检查更新并下载安装?

问题描述

开发的鸿蒙 APP 需要支持应用内更新功能,用户打开 APP 后自动检查 AGC 上的最新版本,若有更新则提示用户下载安装,如何实现版本检查、Apk/Hap 下载和自动安装?是否需要申请特殊权限?关键字:鸿蒙应用内更新、AGC 版本检查、Hap 下载、自动安装、权限申请

回答内容

原理解析

鸿蒙应用内更新核心流程:

  1. 从 AGC 获取最新版本信息(版本号、下载地址);
  2. 对比本地版本与最新版本,若有更新则提示用户;
  3. 通过 HTTP 下载最新 Hap/Apk 安装包;
  4. 调用系统安装接口完成安装,核心依赖 AGC 的 “应用更新服务” 和鸿蒙的appInstaller API。

实现步骤

步骤 1:申请相关权限

在module.json5中声明权限:

json5

收起
自动换行
深色代码主题
复制
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.REQUEST_INSTALL_APKS",
        "reason": "需要安装应用更新包",
        "usedScene": { "ability": [".MainAbility"], "when": "inuse" }
      },
      {
        "name": "ohos.permission.INTERNET",
        "reason": "需要检查更新和下载安装包",
        "usedScene": { "ability": [".MainAbility"], "when": "inuse" }
      },
      {
        "name": "ohos.permission.WRITE_EXTERNAL_STORAGE",
        "reason": "需要存储下载的安装包",
        "usedScene": { "ability": [".MainAbility"], "when": "inuse" }
      }
    ]
  }
}
步骤 2:从 AGC 获取最新版本信息

typescript

运行

收起
自动换行
深色代码主题
复制
import http from '@ohos.net.http';
import bundle from '@ohos.bundle';
import common from '@ohos.app.ability.common';

class AppUpdateManager {
  private context = getContext(this) as common.UIAbilityContext;
  // AGC应用更新接口(需在AGC控制台开启应用更新服务)
  private agcUpdateUrl = 'https://agc-update-drcn.cloud.huawei.com/checkAppUpdate';

  // 获取本地应用版本号
  async getLocalVersion() {
    const bundleInfo = await bundle.getBundleInfoForSelf(bundle.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
    return bundleInfo.versionName; // 如1.0.0
  }

  // 从AGC检查最新版本
  async checkLatestVersion() {
    const httpRequest = http.createHttp();
    try {
      const localVersion = await this.getLocalVersion();
      const response = await httpRequest.request(this.agcUpdateUrl, {
        method: http.RequestMethod.POST,
        header: { 'Content-Type': 'application/json' },
        extraData: JSON.stringify({
          appId: '你的AGC应用ID',
          bundleName: this.context.bundleName,
          versionName: localVersion
        })
      });

      if (response.responseCode === 200) {
        const result = JSON.parse(response.result.toString());
        // 对比版本号(假设最新版本号为result.latestVersionName)
        if (this.compareVersion(result.latestVersionName, localVersion) > 0) {
          console.log('发现新版本:', result.latestVersionName);
          return {
            hasUpdate: true,
            downloadUrl: result.downloadUrl, // 安装包下载地址
            versionName: result.latestVersionName,
            releaseNotes: result.releaseNotes // 更新日志
          };
        }
      }
      return { hasUpdate: false };
    } catch (err) {
      console.error('检查更新失败:', err);
      return { hasUpdate: false };
    } finally {
      httpRequest.destroy();
    }
  }

  // 版本号对比(如1.1.0 > 1.0.0)
  compareVersion(v1: string, v2: string): number {
    const v1Arr = v1.split('.').map(Number);
    const v2Arr = v2.split('.').map(Number);
    for (let i = 0; i < Math.max(v1Arr.length, v2Arr.length); i++) {
      const num1 = v1Arr[i] || 0;
      const num2 = v2Arr[i] || 0;
      if (num1 > num2) return 1;
      if (num1 < num2) return -1;
    }
    return 0;
  }
}
步骤 3:下载安装包

typescript

运行

收起
自动换行
深色代码主题
复制
import fs from '@ohos.file.fs';

// 下载安装包到沙箱目录
async downloadUpdatePackage(downloadUrl: string): Promise<string> {
  const httpRequest = http.createHttp();
  try {
    const response = await httpRequest.request(downloadUrl, {
      method: http.RequestMethod.GET,
      responseType: http.ResponseType.STREAM
    });

    if (response.responseCode === 200) {
      // 沙箱下载目录
      const cacheDir = await this.context.getCacheDir();
      const savePath = `${cacheDir}/app_update.hap`; // 或.apk

      // 写入文件
      const file = await fs.open(savePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      await fs.write(file.fd, response.result as ArrayBuffer);
      await fs.close(file.fd);
      console.log('安装包下载完成:', savePath);
      return savePath;
    }
    throw new Error('下载失败');
  } catch (err) {
    console.error('下载安装包失败:', err);
    throw err;
  } finally {
    httpRequest.destroy();
  }
}
步骤 4:自动安装应用

typescript

运行

收起
自动换行
深色代码主题
复制
import appInstaller from '@ohos.app.installer';

// 安装下载的安装包
async installUpdate(savePath: string) {
  try {
    // 检查安装权限
    const atManager = abilityAccessCtrl.createAtManager();
    const status = await atManager.checkPermission(
      abilityAccessCtrl.PermissionType.PERMISSION,
      'ohos.permission.REQUEST_INSTALL_APKS'
    );

    if (status !== abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
      // 申请安装权限
      await atManager.requestPermissionsFromUser(this.context, ['ohos.permission.REQUEST_INSTALL_APKS']);
    }

    // 调用系统安装接口
    const installParam = {
      bundleFilePath: savePath,
      installFlag: appInstaller.InstallFlag.INSTALL_REPLACE_EXISTING // 覆盖安装
    };

    const installResult = await appInstaller.install(installParam);
    if (installResult.resultCode === 0) {
      console.log('安装成功,应用将重启');
    } else {
      console.error('安装失败:', installResult.errorMsg);
    }
  } catch (err) {
    console.error('安装应用失败:', err);
  }
}
步骤 5:整合应用内更新流程

typescript

运行

收起
自动换行
深色代码主题
复制
// 完整更新流程
async checkAndUpdate() {
  const updateInfo = await this.checkLatestVersion();
  if (updateInfo.hasUpdate) {
    // 提示用户更新
    promptAction.showDialog({
      title: `发现新版本${updateInfo.versionName}`,
      message: updateInfo.releaseNotes,
      buttons: [{ text: '取消' }, { text: '立即更新' }]
    }).then(async (result) => {
      if (result.index === 1) {
        const savePath = await this.downloadUpdatePackage(updateInfo.downloadUrl);
        await this.installUpdate(savePath);
      }
    });
  }
}

避坑提醒

  • 需在 AGC 控制台开启 “应用更新服务”,并上传最新版本的 Hap/Apk;
  • 安装权限(REQUEST_INSTALL_APKS)需动态申请,用户同意后才能安装;
  • 下载的安装包需存储在应用沙箱目录,不可存储在外部公共目录;
  • 安装成功后应用会自动重启,需确保用户数据已保存。
点赞
收藏
2
回复
分享
举报
浏览518 发布于2025-12-22 08:45广东
全部评论
最多点赞
最新发布
最早发布
暂无评论
暂无评论
写回答
新增插入模板功能
一键使用模板,快速填写内容,轻松发帖~
知道了
  • 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
  • 如您发布的内容为转载内容,请注明内容来源。

我要发帖子

目录 收起
问题描述
回答内容
了解社区公约,与您携手共创和谐专业的开发者社区。