鸿蒙开发:应用内如何做更新

2025-06-02 13:44:18
117次阅读
0个评论

前言

本文基于Api13

应用更新是开发中一个比较常见的功能,便于我们把新的功能及时的推送出去,进而提醒用户有新的版本,便于用户及时的去体验下载,可以说,关系着我们APP功能的未来走向,是一个不能缺失而且非常重要的功能。

鸿蒙中的更新和Android有着非常大的区别,在Android中,apk可以自由下载安装,也就意味着,我们可以把apk托管到一个服务器中,在应用中就能让用户做到更新下载,而且非常的及时;然而鸿蒙中却做不到,鸿蒙中打出的包,由于纯净模式默认开启,只能上传到华为应用市场,在其他的渠道是无法进行更新下载的,目的也很明确,为了软件的安全,防止恶意软件入侵。

总结就是,在鸿蒙中更新应用,是无法做到直接下载更新的,而是必须到应用市场进行更新。

从另一个角度来看,对于开发者的我们确实简单了很多,不用在去考虑下载安装的逻辑,也不用考虑后台更新的逻辑,只需要调用系统给我们提供的更新方法就可以了。

更新呢,也有两种方式,一种是直接使用系统提供的更新样式,另一种就是自定义更新弹窗样式,无论哪种样式,最后都是需要跳转到应用市场。

调用系统更新样式

调用系统样式,非常的简单,无须我们再额外的处理弹窗样式,所有的功能从检查更新到弹窗,都有系统来提供,也就是通过updateManager里的两个方法,一个是checkAppUpdate检查更新,一个showUpdateDialog显示更新弹窗,源码如下:

  /**
     * Check for Update.
     *
     * @param { common.UIAbilityContext } context - the context of an ability
     * @returns { Promise<CheckUpdateResult> } The promise of CheckUpdateResult returned by the function.
     * @throws { BusinessError } 401 - Parameter error.
     * @throws { BusinessError } 1009400001 - SA connect error
     * @throws { BusinessError } 1009400002 - Request to service error.
     * @throws { BusinessError } 1009400003 - Network error.
     * @throws { BusinessError } 1009400004 - The application is not in the foreground.
     * @throws { BusinessError } 1009400005 - Not agreeing to the privacy agreement.
     * @throws { BusinessError } 1009400006 - Time limited.
     * @throws { BusinessError } 1009400007 - Other error.
     * @syscap SystemCapability.AppGalleryService.Distribution.Update
     * @stagemodelonly
     * @since 5.0.0(12)
     */
    function checkAppUpdate(context: common.UIAbilityContext): Promise<CheckUpdateResult>;
    /**
     * Displaying the update dialog.
     *
     * @param { common.UIAbilityContext} context - the context of an ability
     * @returns { Promise<ShowUpdateResultCode> } The promise of ShowUpdateResultCode returned by the function.
     * @throws { BusinessError } 401 - Parameter error.
     * @throws { BusinessError } 1009400001 - SA connection error.
     * @throws { BusinessError } 1009400002 - Request to service error.
     * @throws { BusinessError } 1009400004 - The application is not in the foreground.
     * @throws { BusinessError } 1009400005 - Not agreeing to the privacy agreement.
     * @throws { BusinessError } 1009400007 - Other error.
     * @syscap SystemCapability.AppGalleryService.Distribution.Update
     * @stagemodelonly
     * @since 5.0.0(12)
     */
    function showUpdateDialog(context: common.UIAbilityContext): Promise<ShowUpdateResultCode>;

需要注意的是,两者必须结合使用,先去检查,再去显示更新弹窗,我们可以按照下面的代码逻辑去执行,在调用的时候,直接调用checkAppUpdate方法即可。

/**
   * 检查是否有更新,使用Promise方式异步返回结果
   */
  checkAppUpdate() {
    try {
      updateManager.checkAppUpdate(getContext() as common.UIAbilityContext)
        .then((checkResult: updateManager.CheckUpdateResult) => {
          //检查结果
          if (checkResult.updateAvailable == updateManager.UpdateAvailableCode.LATER_VERSION_EXIST) {
            //存在新的版本
            this.showUpdateDialog()
          }
        })
    } catch (error) {
    }
  }

  /**
   * 弹出更新弹窗
   */
  showUpdateDialog() {
    try {
      updateManager.showUpdateDialog(getContext() as common.UIAbilityContext)
    } catch (error) {
    }
  }

由于是返回的Promise,我们可以更加简单的使用await方法,代码更加的简单。

 /**
   * 检查是否有更新,使用Promise方式异步返回结果
   */
  async checkAppUpdate() {
    let context = getContext() as common.UIAbilityContext
    let checkResult = await updateManager.checkAppUpdate(context)
    //检查结果
    if (checkResult.updateAvailable == updateManager.UpdateAvailableCode.LATER_VERSION_EXIST) {
      //存在新的版本
      updateManager.showUpdateDialog(context)
    }
  }

执行之后,就会显示如下的更新的弹窗,点击立即更新后,就会直接跳转到应用市场此应用的详情页面。

image.png

点击立即更新之后:

image.png

自定义弹窗样式

虽然说,鸿蒙不支持应用内更新下载,但是支持你自定义弹窗样式,只不过最后的更新,还是要去应用市场进行,实现步骤,第一步还是要调用系统的检查更新的方法,有更新时弹出自己的弹窗,然后实现跳转到应用市场详情页面。

检查更新

 /**
   * 检查是否有更新,使用Promise方式异步返回结果
   */
  async checkAppUpdate() {
    let context = getContext() as common.UIAbilityContext
    let checkResult = await updateManager.checkAppUpdate(context)
    //检查结果
    if (checkResult.updateAvailable == updateManager.UpdateAvailableCode.LATER_VERSION_EXIST) {
      //存在新的版本,弹出自己的视图,自己去定义

    }
  }

自定义弹窗这里就不写了,大家自行实现即可,当然,这里也推荐一下我的一个弹窗组件,有喜欢的朋友,可以进行体验,中心仓库地址是:

https://ohpm.openharmony.cn/#/cn/detail/@abner%2Fdialog

我这个弹窗,支持八大功能模块,几乎涵盖各个业务需求,【自定义形式】、【时间弹窗】、【城市选择】、【确认&信息】、【底部列表&网格】、【toast】、【popup形式】、【loading形式】,如果还不能满足,还支持便捷式自定义,可以说,让你的弹窗实现更加的便捷。

更新弹窗实现后,无非就是怎么跳转应用详情页面了,目前总结了三种方式,大家可以选择自己喜欢的方式。

跳转市场详情页面

方式一:loadProduct接口调用

主要是通过productViewManager中的loadProduct来拉起应用的详情页面,需要把bundleName替换为你自己的应用包名。

/**
   * productViewManager拉齐应用详情页
   */
  loadProduct() {
    const uiContext = getContext(this) as common.UIAbilityContext
    const wantParam: Want = {
      parameters: {
        // 必填,此处填入要加载的应用包名,例如: bundleName: 'com.huawei.hmsapp.books'
        bundleName: 'com.xx.xx',
      }
    }
    const callback: productViewManager.ProductViewCallback = {
      onError: (error: BusinessError) => {
        hilog.error(0, 'TAG', `loadService onError.code is ${error.code}, message is ${error.message}`)
      },
      onAppear: () => {
        hilog.info(0, 'TAG', `loadProduct onAppear.`);
      },
      onDisappear: () => {
        hilog.info(0, 'TAG', `loadProduct onDisappear.`);
      }
    }
    // 调用接口,拉起应用详情页
    productViewManager.loadProduct(uiContext, wantParam, callback);
  }

调用以上的方法后,就会跳转到应用的详情页面。

方式二:DeepLink方式

DeepLink方式是通过startAbility的方式进行跳转应用详情页面,也是需要应用的包名,其格式为:

store://appgallery.huawei.com/app/detail?id= + bundleName

实现跳转代码如下,定义外部的function函数。

// 拉起应用市场对应的应用详情页面
function startAppGalleryDetailAbility(context: common.UIAbilityContext, bundleName: string): void {
  let want: Want = {
    action: 'ohos.want.action.appdetail', //隐式指定action为ohos.want.action.appdetail
    uri: 'store://appgallery.huawei.com/app/detail?id=' + bundleName, //  bundleName为需要打开应用详情的应用包名
  };
  context.startAbility(want).then(() => {
    hilog.info(0x0001, 'TAG', "Succeeded in starting Ability successfully.")
  }).catch((error: BusinessError) => {
    hilog.error(0x0001, 'TAG', `Failed to startAbility.Code: ${error.code}, message is ${error.message}`);
  });
}

在需要跳转的时候,直接调佣,传入上下文和包名即可:

  startAppGalleryDetailAbility(getContext() as common.UIAbilityContext,"com.xx.xx")

方式三:App Linking方式

App Linking的方式是通过openLink的方式跳转到应用市场详情页面,同样也是需要包名。其格式为:

https://appgallery.huawei.com/app/detail?id= + bundleName

跳转代码如下:

openLink(){
    let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
    // 需要拼接不同的应用包名,用以打开不同的应用详情页,例如:bundleName: 'com.huawei.hmsapp.books'
    let bundleName: string = 'com.xx.xx';
    let link: string = 'https://appgallery.huawei.com/app/detail?id=' + bundleName;
    // 以App Linking优先的方式在应用市场打开指定包名的应用详情页
    context.openLink(link, { appLinkingOnly: false })
      .then(() => {
        hilog.info(0x0001, 'TAG', 'openlink success.');
      })
      .catch((error: BusinessError) => {
        hilog.error(0x0001, 'TAG', `openlink failed. Code: ${error.code}, message is ${error.message}`);
      });
  }

相关总结

使用系统的,直接调用检查和显示更新弹窗即可,可以说就两个方法,我们就实现了应用更新的功能,可以说是非常的简单,如果系统的弹窗无法满足您的需求,您可以自定义弹窗,然后实现跳转应用详情页面即可。

本文标签:鸿蒙开发工具/应用更新

收藏00

登录 后评论。没有帐号? 注册 一个。