import bundleManager from '@ohos.bundle.bundleManager';
import { KeyboardAvoidMode, window } from '@kit.ArkUI';
import { common, ConfigurationConstant } from '@kit.AbilityKit';

/**
 * App相关工具类(使用该工具前请在UIAbility的onWindowStageCreate方法中调用AppUtil的init方法初始化)
 * author: 鸿蒙布道师
 * since: 2024/03/25
 */
export class AppUtil {
  private static context: common.UIAbilityContext; // 上下文

  /**
   * 初始化方法,缓存全局变量,在UIAbility的onCreate方法中初始化该方法。
   * @param context UIAbility上下文
   */
  static init(context: common.UIAbilityContext) {
    AppUtil.context = context;
  }

  /**
   * 获取上下文,common.UIAbilityContext
   * @returns UIAbility上下文
   */
  static getContext(): common.UIAbilityContext {
    if (!AppUtil.context) {
      throw new Error("请在UIAbility的onCreate方法中调用AppUtil的init方法初始化!");
    }
    return AppUtil.context;
  }

  /**
   * 获取WindowStage
   * @returns WindowStage
   */
  static getWindowStage(): window.WindowStage {
    return AppUtil.getContext().windowStage;
  }

  /**
   * 获取主窗口
   * @returns 主窗口
   */
  static getMainWindow(): window.Window {
    return AppUtil.getWindowStage().getMainWindowSync();
  }

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

  /**
   * 设置灰阶,APP一键置灰。
   * @param grayScale 该参数为浮点数,取值范围为[0.0, 1.0]。
   * @param onlyMainWindow 是否只置灰主窗口,默认false。
   */
  static async setGrayScale(grayScale: number = 1.0, onlyMainWindow: boolean = false): Promise<void> {
    AppUtil.getMainWindow().setWindowGrayScale(grayScale);
    if (!onlyMainWindow) {
      const subWindows = await AppUtil.getWindowStage().getSubWindow();
      subWindows?.forEach((subWindow) => subWindow.setWindowGrayScale(grayScale));
    }
  }

  /**
   * 设置应用的颜色模式。仅支持主线程调用。
   * @param colorMode 颜色模式
   */
  static setColorMode(colorMode: ConfigurationConstant.ColorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET) {
    AppUtil.getContext().getApplicationContext().setColorMode(colorMode);
  }

  /**
   * 设置应用的字体类型。仅支持主线程调用。
   * @param font 字体类型
   */
  static setFont(font: string) {
    AppUtil.getContext().getApplicationContext().setFont(font);
  }

  /**
   * 获取当前窗口的属性
   * @param windowClass 窗口实例,默认主窗口
   * @returns 窗口属性
   */
  static getWindowProperties(windowClass: window.Window = AppUtil.getMainWindow()): window.WindowProperties {
    return windowClass.getWindowProperties();
  }

  /**
   * 获取虚拟键盘抬起时的页面避让模式
   * @returns 避让模式
   */
  static getKeyboardAvoidMode(): KeyboardAvoidMode {
    const mode = AppUtil.getUIContext().getKeyboardAvoidMode();
    if(typeof mode === 'string'){
      return mode === "KeyBoardAvoidMode.RESIZE" ? KeyboardAvoidMode.RESIZE : KeyboardAvoidMode.OFFSET;
    }
    return mode;
  }

  /**
   * 设置虚拟键盘弹出时,页面的避让模式。
   * @param value 避让模式
   * @returns 是否设置成功
   */
  static setKeyboardAvoidMode(value: KeyboardAvoidMode): boolean {
    try {
      AppUtil.getUIContext().setKeyboardAvoidMode(value);
      return true;
    } catch (err) {
      console.error('设置键盘避让模式失败:', err);
      return false;
    }
  }

  /**
   * 设置窗口的显示方向属性
   * @param orientation 显示方向
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setPreferredOrientation(orientation: window.Orientation, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setPreferredOrientation(orientation);
  }

  /**
   * 设置屏幕亮度值
   * @param brightness 屏幕亮度值,取值范围为[0.0, 1.0]或-1.0
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowBrightness(brightness: number, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowBrightness(brightness);
  }

  /**
   * 设置屏幕是否为常亮状态
   * @param isKeepScreenOn 是否常亮
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowKeepScreenOn(isKeepScreenOn: boolean, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowKeepScreenOn(isKeepScreenOn);
  }

  /**
   * 设置窗口是否为隐私模式
   * @param isPrivacyMode 是否隐私模式
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowPrivacyMode(isPrivacyMode: boolean, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowPrivacyMode(isPrivacyMode);
  }

  /**
   * 设置窗口的背景色
   * @param color 背景色
   * @param windowClass 窗口实例,默认主窗口
   */
  static setWindowBackgroundColor(color: string, windowClass: window.Window = AppUtil.getMainWindow()) {
    try {
      windowClass.setWindowBackgroundColor(color);
    } catch (err) {
      console.error('设置窗口背景色失败:', err);
    }
  }

  /**
   * 设置点击时是否支持切换焦点窗口
   * @param isFocusable 是否支持切换焦点窗口
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowFocusable(isFocusable: boolean, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowFocusable(isFocusable);
  }

  /**
   * 设置窗口是否为可触状态
   * @param isTouchable 是否可触
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowTouchable(isTouchable: boolean, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowTouchable(isTouchable);
  }

  /**
   * 获取状态栏的高度,单位为px。
   * @returns 状态栏高度
   */
  static getStatusBarHeight(): number {
    try {
      const avoidArea = AppUtil.getMainWindow().getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
      return avoidArea.topRect.height;
    } catch (err) {
      console.error('获取状态栏高度失败:', err);
      return 0;
    }
  }

  /**
   * 获取底部导航条的高度,单位为px。
   * @returns 导航条高度
   */
  static getNavigationIndicatorHeight(): number {
    try {
      const avoidArea = AppUtil.getMainWindow().getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
      return avoidArea.bottomRect.height;
    } catch (err) {
      console.error('获取导航条高度失败:', err);
      return 0;
    }
  }

  /**
   * 设置沉浸式状态栏
   * @param isLayoutFullScreen 是否沉浸式布局
   * @param enable 是否显示状态栏和导航栏
   * @param color 窗口背景颜色
   * @param systemBarProperties 状态栏和导航栏属性
   */
  static async setStatusBar(isLayoutFullScreen: boolean = true, enable: boolean = true, color: string = '#FFFFFF', systemBarProperties?: window.SystemBarProperties) {
    try {
      const windowClass = AppUtil.getMainWindow();
      await windowClass.setWindowLayoutFullScreen(isLayoutFullScreen);
      windowClass.setWindowBackgroundColor(color);
      await windowClass.setWindowSystemBarEnable(enable ? ['status', 'navigation'] : []);
      await windowClass.setSpecificSystemBarEnabled("navigationIndicator", enable);
      if (systemBarProperties) {
        await windowClass.setWindowSystemBarProperties(systemBarProperties);
      }
    } catch (err) {
      console.error('设置沉浸式状态栏失败:', err);
    }
  }

  /**
   * 获取当前应用的BundleInfo
   * @param sync 是否同步获取,默认异步
   * @returns BundleInfo
   */
  static async getBundleInfo(sync: boolean = false): Promise<bundleManager.BundleInfo> {
    return sync ? bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION) : bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
  }

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

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

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

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

  /**
   * 获取应用程序的配置信息
   * @returns 应用信息
   */
  static async getAppInfo(): Promise<bundleManager.ApplicationInfo> {
    const bundleInfo = await AppUtil.getBundleInfo();
    return bundleInfo.appInfo;
  }

  /**
   * 主动退出整个应用
   */
  static exit() {
    AppUtil.getContext().terminateSelf();
    AppUtil.getContext().getApplicationContext().killAllProcesses();
  }
}

代码如下:

import bundleManager from '@ohos.bundle.bundleManager';
import { KeyboardAvoidMode, window } from '@kit.ArkUI';
import { common, ConfigurationConstant } from '@kit.AbilityKit';

/**
 * App相关工具类(使用该工具前请在UIAbility的onWindowStageCreate方法中调用AppUtil的init方法初始化)
 * author: 鸿蒙布道师
 * since: 2024/03/25
 */
export class AppUtil {
  private static context: common.UIAbilityContext; // 上下文

  /**
   * 初始化方法,缓存全局变量,在UIAbility的onCreate方法中初始化该方法。
   * @param context UIAbility上下文
   */
  static init(context: common.UIAbilityContext) {
    AppUtil.context = context;
  }

  /**
   * 获取上下文,common.UIAbilityContext
   * @returns UIAbility上下文
   */
  static getContext(): common.UIAbilityContext {
    if (!AppUtil.context) {
      throw new Error("请在UIAbility的onCreate方法中调用AppUtil的init方法初始化!");
    }
    return AppUtil.context;
  }

  /**
   * 获取WindowStage
   * @returns WindowStage
   */
  static getWindowStage(): window.WindowStage {
    return AppUtil.getContext().windowStage;
  }

  /**
   * 获取主窗口
   * @returns 主窗口
   */
  static getMainWindow(): window.Window {
    return AppUtil.getWindowStage().getMainWindowSync();
  }

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

  /**
   * 设置灰阶,APP一键置灰。
   * @param grayScale 该参数为浮点数,取值范围为[0.0, 1.0]。
   * @param onlyMainWindow 是否只置灰主窗口,默认false。
   */
  static async setGrayScale(grayScale: number = 1.0, onlyMainWindow: boolean = false): Promise<void> {
    AppUtil.getMainWindow().setWindowGrayScale(grayScale);
    if (!onlyMainWindow) {
      const subWindows = await AppUtil.getWindowStage().getSubWindow();
      subWindows?.forEach((subWindow) => subWindow.setWindowGrayScale(grayScale));
    }
  }

  /**
   * 设置应用的颜色模式。仅支持主线程调用。
   * @param colorMode 颜色模式
   */
  static setColorMode(colorMode: ConfigurationConstant.ColorMode = ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET) {
    AppUtil.getContext().getApplicationContext().setColorMode(colorMode);
  }

  /**
   * 设置应用的字体类型。仅支持主线程调用。
   * @param font 字体类型
   */
  static setFont(font: string) {
    AppUtil.getContext().getApplicationContext().setFont(font);
  }

  /**
   * 获取当前窗口的属性
   * @param windowClass 窗口实例,默认主窗口
   * @returns 窗口属性
   */
  static getWindowProperties(windowClass: window.Window = AppUtil.getMainWindow()): window.WindowProperties {
    return windowClass.getWindowProperties();
  }

  /**
   * 获取虚拟键盘抬起时的页面避让模式
   * @returns 避让模式
   */
  static getKeyboardAvoidMode(): KeyboardAvoidMode {
    const mode = AppUtil.getUIContext().getKeyboardAvoidMode();
    if(typeof mode === 'string'){
      return mode === "KeyBoardAvoidMode.RESIZE" ? KeyboardAvoidMode.RESIZE : KeyboardAvoidMode.OFFSET;
    }
    return mode;
  }

  /**
   * 设置虚拟键盘弹出时,页面的避让模式。
   * @param value 避让模式
   * @returns 是否设置成功
   */
  static setKeyboardAvoidMode(value: KeyboardAvoidMode): boolean {
    try {
      AppUtil.getUIContext().setKeyboardAvoidMode(value);
      return true;
    } catch (err) {
      console.error('设置键盘避让模式失败:', err);
      return false;
    }
  }

  /**
   * 设置窗口的显示方向属性
   * @param orientation 显示方向
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setPreferredOrientation(orientation: window.Orientation, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setPreferredOrientation(orientation);
  }

  /**
   * 设置屏幕亮度值
   * @param brightness 屏幕亮度值,取值范围为[0.0, 1.0]或-1.0
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowBrightness(brightness: number, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowBrightness(brightness);
  }

  /**
   * 设置屏幕是否为常亮状态
   * @param isKeepScreenOn 是否常亮
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowKeepScreenOn(isKeepScreenOn: boolean, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowKeepScreenOn(isKeepScreenOn);
  }

  /**
   * 设置窗口是否为隐私模式
   * @param isPrivacyMode 是否隐私模式
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowPrivacyMode(isPrivacyMode: boolean, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowPrivacyMode(isPrivacyMode);
  }

  /**
   * 设置窗口的背景色
   * @param color 背景色
   * @param windowClass 窗口实例,默认主窗口
   */
  static setWindowBackgroundColor(color: string, windowClass: window.Window = AppUtil.getMainWindow()) {
    try {
      windowClass.setWindowBackgroundColor(color);
    } catch (err) {
      console.error('设置窗口背景色失败:', err);
    }
  }

  /**
   * 设置点击时是否支持切换焦点窗口
   * @param isFocusable 是否支持切换焦点窗口
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowFocusable(isFocusable: boolean, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowFocusable(isFocusable);
  }

  /**
   * 设置窗口是否为可触状态
   * @param isTouchable 是否可触
   * @param windowClass 窗口实例,默认主窗口
   */
  static async setWindowTouchable(isTouchable: boolean, windowClass: window.Window = AppUtil.getMainWindow()): Promise<void> {
    return windowClass.setWindowTouchable(isTouchable);
  }

  /**
   * 获取状态栏的高度,单位为px。
   * @returns 状态栏高度
   */
  static getStatusBarHeight(): number {
    try {
      const avoidArea = AppUtil.getMainWindow().getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
      return avoidArea.topRect.height;
    } catch (err) {
      console.error('获取状态栏高度失败:', err);
      return 0;
    }
  }

  /**
   * 获取底部导航条的高度,单位为px。
   * @returns 导航条高度
   */
  static getNavigationIndicatorHeight(): number {
    try {
      const avoidArea = AppUtil.getMainWindow().getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
      return avoidArea.bottomRect.height;
    } catch (err) {
      console.error('获取导航条高度失败:', err);
      return 0;
    }
  }

  /**
   * 设置沉浸式状态栏
   * @param isLayoutFullScreen 是否沉浸式布局
   * @param enable 是否显示状态栏和导航栏
   * @param color 窗口背景颜色
   * @param systemBarProperties 状态栏和导航栏属性
   */
  static async setStatusBar(isLayoutFullScreen: boolean = true, enable: boolean = true, color: string = '#FFFFFF', systemBarProperties?: window.SystemBarProperties) {
    try {
      const windowClass = AppUtil.getMainWindow();
      await windowClass.setWindowLayoutFullScreen(isLayoutFullScreen);
      windowClass.setWindowBackgroundColor(color);
      await windowClass.setWindowSystemBarEnable(enable ? ['status', 'navigation'] : []);
      await windowClass.setSpecificSystemBarEnabled("navigationIndicator", enable);
      if (systemBarProperties) {
        await windowClass.setWindowSystemBarProperties(systemBarProperties);
      }
    } catch (err) {
      console.error('设置沉浸式状态栏失败:', err);
    }
  }

  /**
   * 获取当前应用的BundleInfo
   * @param sync 是否同步获取,默认异步
   * @returns BundleInfo
   */
  static async getBundleInfo(sync: boolean = false): Promise<bundleManager.BundleInfo> {
    return sync ? bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION) : bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION);
  }

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

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

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

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

  /**
   * 获取应用程序的配置信息
   * @returns 应用信息
   */
  static async getAppInfo(): Promise<bundleManager.ApplicationInfo> {
    const bundleInfo = await AppUtil.getBundleInfo();
    return bundleInfo.appInfo;
  }

  /**
   * 主动退出整个应用
   */
  static exit() {
    AppUtil.getContext().terminateSelf();
    AppUtil.getContext().getApplicationContext().killAllProcesses();
  }
}

 

 

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐