AppUtils.ets 1.45 KB
import bundleManager from '@ohos.bundle.bundleManager';
import common from '@ohos.app.ability.common';
import { Logger } from './Logger';

const TAG: string = 'AppUtils';

/**
 * 与应用相关属性或操作
 */
export class AppUtils {
  /**
   * 获取应用名称
   * 即:咪咕视频
   */
  static getAppName(context: common.Context): string {
    // todo:获取到的是 $string:app_name
    // return context.applicationInfo?.label;
    return context.resourceManager.getStringByNameSync("app_name");
  }

  /**
   * 获取应用的包名
   * 即:com.cmcc.myapplication
   */
  static getPackageName(context: common.Context): string {
    return context.applicationInfo?.name;
  }

  /**
   * 获取应用版本号,如:1.0.0.0
   * @returns 版本号字符串
   */
  static getAppVersionName(): string {
    try {
      let bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT)
      return bundleInfo?.versionName
    } catch (e) {
      Logger.warn(TAG, 'get app version error:' + e?.message);
    }
    return "";
  }

  /**
   * 获取应用版本编码,如:1000000
   * @returns 应用版本编码
   */
  static getAppVersionCode(): string {
    try {
      let bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT)
      return bundleInfo?.versionCode + ""
    } catch (e) {
      Logger.warn(TAG, 'get app version error:' + e?.message);
    }
    return '';
  }
}