HarmonyOS鸿蒙Next中如何获取打包安装时的时间作为应用版本号

HarmonyOS鸿蒙Next中如何获取打包安装时的时间作为应用版本号 有一个需求场景式希望获取打包时间作为版本号的字符之一,想请问如何时间获取打包时间。

  1. 不是简单的获取时间,希望类似安卓一样可以在build.gradle文件进行代码编写,所有打包项目时运行build.gradle文件,后续安装的时候读取的都是这个时间。

  2. 如果读取版本号,目前我只能实现读取app.json文件的版本信息,请问在设计上是否是建议如此?

4 回复

可以通过开发Hvigor插件的方式开发hvigorfile.ts脚本在编译构建阶段实现这样的场景,参考资料开发Hvigor插件、扩展构建API章节:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/ide-hvigor-plugin-0000001778674577-V5

可以尝试下Hvigor相关API在OpenHarmony的工程下的支持能力,根据其支持能力完成脚本开发。

更多关于HarmonyOS鸿蒙Next中如何获取打包安装时的时间作为应用版本号的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


可使用bundleManager.getBundleInfoForSelf接口获取BundleInfo,其中有versionCode、versionName,可以参考文档:https://developer.harmonyos.com/cn/docs/documentation/doc-references-V4/js-apis-bundlemanager-0000001580185550-V4#ZH-CN_TOPIC_0000001666707696__bundlemanagergetbundleinfoforself

在HarmonyOS(鸿蒙)Next中,获取打包安装时的时间作为应用版本号,可以通过以下步骤实现:

  1. 使用构建工具自动生成版本号:在HarmonyOS的开发过程中,可以使用构建工具(如Gradle)在打包时自动生成时间戳,并将其作为应用版本号的一部分。可以在build.gradle文件中添加脚本,获取当前时间并赋值给versionNameversionCode

    def getBuildTime() {
        return new Date().format("yyyyMMddHHmmss", TimeZone.getTimeZone("GMT+08:00"))
    }
    
    android {
        defaultConfig {
            versionName getBuildTime()
            versionCode Integer.parseInt(getBuildTime())
        }
    }
    
  2. 使用HarmonyOS API获取安装时间:在应用运行时,可以通过HarmonyOS提供的BundleManagerAppInfo相关API获取应用的安装时间。例如,使用BundleManager.getBundleInfo()方法获取应用的安装时间戳。

    import bundleManager from '[@ohos](/user/ohos).bundle.bundleManager';
    
    let bundleName = 'com.example.myapp';
    bundleManager.getBundleInfo(bundleName, bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO).then((data) => {
        let installTime = data.installTime;
        console.log("App install time: " + installTime);
    });
    
  3. 将时间戳转换为版本号格式:获取到时间戳后,可以根据需要将其转换为特定的版本号格式。例如,将时间戳转换为YYYY.MM.DD.HHmm格式,作为versionName

    let installTime = data.installTime;
    let date = new Date(instTime);
    let versionName = date.getFullYear() + "." + (date.getMonth() + 1) + "." + date.getDate() + "." + date.getHours() + date.getMinutes();
    

通过以上方法,可以在HarmonyOS Next中获取打包安装时的时间,并将其作为应用版本号。

在HarmonyOS鸿蒙Next中,可以通过BundleManager获取应用的安装时间。使用BundleManager.getBundleInfo()方法获取BundleInfo对象,其中包含了应用的安装时间戳。你可以将时间戳转换为日期格式,并作为应用版本号的一部分。示例代码:

BundleManager bundleManager = getBundleManager();
BundleInfo bundleInfo = bundleManager.getBundleInfo(getBundleName(), 0);
long installTime = bundleInfo.getInstallTime();
String version = new SimpleDateFormat("yyyyMMdd").format(new Date(installTime));

version作为应用版本号即可。

回到顶部