HarmonyOS获取App相关信息封装与使用指南

45 阅读2分钟

1、封装App信息管理类:

import { bundleManager, common, Want } from '@kit.AbilityKit';
import { window } from '@kit.ArkUI';
import { LoggerManager } from './LoggerManager';
import { call } from '@kit.TelephonyKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Contact } from '../models/Contact';
import { NavEntryKey } from '../models/NavEntryKey';

/**
 * App管理类
 */
export class AppManager {
  private static context: common.UIAbilityContext // common.UIAbilityContext,上下文
  private static windowStage: window.WindowStage

  /**
   * 初始化方法,缓存全局变量,在UIAbility的onWindowStageCreate方法中初始化该方法。
   * @param windowStage 窗口管理器
   */
  static init(context: common.UIAbilityContext, windowStage: window.WindowStage) {
    AppManager.context = context;
    AppManager.windowStage = windowStage;
  }

  /**
   * 获取上下文,common.UIAbilityContext
   * @returns
   */
  static getContext(): common.UIAbilityContext {
    if (!AppManager.context) {
      AppManager.context = getContext() as common.UIAbilityContext; //兜底
      LoggerManager.error("context为空,请在UIAbility的onWindowStageCreate方法中调用AppManager的init方法初始化!");
    }
    return AppManager.context;
  }

  /**
   * 获取主窗口
   */
  static getMainWindow(): window.Window {
    if (!AppManager.windowStage) {
      LoggerManager.error("windowStage为空,请在UIAbility的onWindowStageCreate方法中调用AppUtil的init方法初始化!");
    }
    return AppManager.windowStage.getMainWindowSync();
  }

  /**
   * 获取UIContext
   * @returns
   */
  static getUIContext(): UIContext {
    return AppManager.getMainWindow().getUIContext();
  }

  /**
   * 获取当前应用的BundleInfo
   * @returns
   */
  static async getBundleInfo(): Promise<bundleManager.BundleInfo> {
    return await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
  }

  /**
   * 获取应用包的名称
   * @returns
   */
  static async getBundleName(): Promise<string> {
    return (await AppManager.getBundleInfo()).name
  }

  /**
   * 获取应用版本号
   * @returns
   */
  static async getVersionCode(): Promise<number> {
    return (await AppManager.getBundleInfo()).versionCode
  }

  /**
   * 获取应用版本名
   * @returns
   */
  static async getVersionName(): Promise<string> {
    return (await AppManager.getBundleInfo()).versionName
  }

  /**
   * 比较版本号
   * @param currentVersion
   * @param lastVersion
   * @returns 1:当前版本 > 最新版本,-1:当前版本 < 最新版本,0:当前版本 = 最新版本
   */
  static compareVersion(currentVersion: string, lastVersion: string): number {
    const verArr1 = currentVersion.split('.').map(Number);
    const verArr2 = lastVersion.split('.').map(Number);

    const len = Math.max(verArr1.length, verArr2.length);

    for (let i = 0; i < len; i++) {
      // 如果长度不一致,缺失的部分用0补齐
      const num1 = verArr1[i] || 0;
      const num2 = verArr2[i] || 0;

      if (num1 > num2) {
        return 1;
      } else if (num1 < num2) {
        return -1;
      }
    }
    return 0;
  }


  /**
   * 获取运行应用包所需要最高SDK版本号
   * @returns
   */
  static async getTargetVersion(): Promise<number> {
    return (await AppManager.getBundleInfo()).targetVersion
  }


  /**
   * 获取应用程序的配置信息
   * @returns
   */
  static async getAppInfo() {
    let bundleInfo: bundleManager.BundleInfo =
      await bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
    return bundleInfo.appInfo
  }

}

2、调用侧页面代码示例

Text('App信息')
Button('app包')
  .onClick(async () => {
    let bundleInfo = await AppManager.getBundleInfo()
    AlertDialog.show({ message: JSON.stringify(bundleInfo, null, 2) })
  })
Button('app包名')
  .onClick(async () => {
    let bundleName = await AppManager.getBundleName()
    promptAction.showToast({ message: 'app包名:' + bundleName })
  })
Button('app版本号')
  .onClick(async () => {
    let versionCode = await AppManager.getVersionCode()
    promptAction.showToast({ message: 'app版本号:' + versionCode })
  })
Button('app版本名')
  .onClick(async () => {
    let versionName = await AppManager.getVersionName()
    promptAction.showToast({ message: 'app版本名:' + versionName })
  })

Button('检查新版本')
  .fontColor($r('sys.color.black'))
  .onClick(async () => {
    let versionCode = (await AppManager.getVersionName()).toString()
    let result = AppManager.compareVersion(versionCode, versionCode)
    if (result > 0) {
      promptAction.showToast({ message: '有新版本' })
    } else {
      promptAction.showToast({ message: '当前版本为最新版本' })
    }
  })

Button('app配置信息')
  .onClick(async () => {
    let appInfo = await AppManager.getAppInfo()
    AlertDialog.show({ message: JSON.stringify(appInfo, null, 2) })
  })
Button('app运行所需最低SDK版本号')
  .onClick(async () => {
    let targetVersion = await AppManager.getTargetVersion()
    promptAction.showToast({ message: 'app运行所需最低SDK版本号:' + targetVersion })
  })

3、效果示例图

PixPin_2025-09-03_16-03-48.png