HarmonyOS 鸿蒙Next 如何同步获取App的版本号?

HarmonyOS 鸿蒙Next 如何同步获取App的版本号? 在网络库中需要获取App的版本号,网络库是一个har包,通过如下方法获得版本号是异步的,无法满足需求。

bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo) => {
  this._appFullVersion = bundleInfo.versionName
})

请提供一个如何同步获取app版本号的方法。

2 回复

bundleManager.getBundleInfoForSelfSync()

更多关于HarmonyOS 鸿蒙Next 如何同步获取App的版本号?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS(鸿蒙Next)中,要同步获取App的版本号,可以使用`BundleManager`和`ApplicationInfo`类来完成。具体步骤如下:

1. 获取`BundleManager`实例:
   ```typescript
   let bundleManager = context.getBundleManager();
  1. 使用BundleManager获取当前应用的ApplicationInfo

    let applicationInfo = await bundleManager.getApplicationInfo(context.getBundleName(), 0);
    
  2. ApplicationInfo中提取版本号:

    let versionName = applicationInfo.versionName;
    let versionCode = applicationInfo.versionCode;
    

versionName是字符串类型的版本名称(如"1.0.0"),versionCode是数字类型的版本代码(如1)。这两个属性分别代表了应用的用户可见版本和内部版本号。

注意:getApplicationInfo是异步方法,但通过await可以将其转换为同步操作。

示例代码:

import featureAbility from '[@ohos](/user/ohos).ability.featureAbility';

let context = featureAbility.getContext();
let bundleManager = context.getBundleManager();
let applicationInfo = await bundleManager.getApplicationInfo(context.getBundleName(), 0);
let versionName = applicationInfo.versionName;
let versionCode = applicationInfo.versionCode;

这样,你就可以同步获取到App的版本号和版本名称了。

回到顶部