鸿蒙next 获取versionCode和versionName

165 阅读1分钟

9ef94ce52720495f995f737393daa0d2~tplv-73owjymdk6-jj-mark-v1_0_0_0_0_5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5Z2a5p6c5rS-X3hxOTUyNw==_q75.webp

前言导读

各位同学在实战开发中,是不是会遇到这样需求 服务端让你把你的app的versionCode版本号和versionName版本名,加入到公共参数里面 然后一起上传到服务端号分析数据呢。

效果图

image.png

具体实现

  • 获取versionName


/***
 *
 *  获取app版本号 versionName
 *
 */
public getVerisonName(): Promise <string> {
  return bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
    .then((bundleInfo) => bundleInfo.versionName)
    .catch(() => "");
}
  • 获取versionCode

/**
 *
 * 获取appversioncode
 * @returns
 */
public getVerisonNo(): Promise <string>{
  return bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
    .then((bundleInfo) => bundleInfo.versionCode.toString())
    .catch(() => "");

}

这里特别注意因为这获取versioncode和versionname 是异步获取 我们不能直接返回 需要使用 : Promise 返回 然后调用地方使用then回调去取值不然是拿不到值的

具体获取展示

import {SystemUtils} from '../utils/SystemUtils'


@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  @State versionCode:string='';
  @State versionName:string='';



  build() {
     Column(){
       Button('获取versionCode').onClick(()=>{
         SystemUtils.getInstance().getVerisonNo().then((data)=>{
           this.versionCode=data;
         })
       })

       Text(this.versionCode)
         . fontSize(20)
         .fontColor(Color.Black)
         .margin({top:20})

       Button('获取versionName').onClick(()=>{
         SystemUtils.getInstance().getVerisonName().then((data)=>{
           this.versionName=data;
         })
       }).margin({top:20})


       Text(this.versionName)
         . fontSize(20)
         .fontColor(Color.Black).margin({top:20})
     }
    .height('100%')
    .width('100%')
  }
}