HarmonyOS鸿蒙Next中通过订阅系统环境变量变化的几种方式怎么获取设备横竖屏的状态变化通知?

HarmonyOS鸿蒙Next中通过订阅系统环境变量变化的几种方式怎么获取设备横竖屏的状态变化通知?

3 回复
  1. ApplicationContext 订阅:这是全局的应用上下文,适合需要在整个应用范围内监听的场景。需要获取 ApplicationContext 实例,调用 registerConfigurationObserver 方法,实现 ConfigurationObserver 接口,在 onConfigurationUpdated 中处理变化。注意需要在适当时候注销,避免内存泄漏。

  2. AbilityStage 订阅:AbilityStage 是 HAP 包的生命周期管理组件,适合监听当前 HAP 内的配置变化。在 AbilityStage 的 onCreate 中注册观察者,同样实现接口,处理回调。

  3. UIAbility 订阅:UIAbility 是应用的基本组件,每个 UIAbility 实例可以独立监听。在 UIAbility 的 onCreate 或 onWindowStageCreate 中注册,或者直接重写自身的 onConfigurationUpdate 方法(因为 UIAbility 本身可能继承了该方法),更方便。

  4. ExtensionAbility 订阅:针对扩展能力组件,比如 ServiceExtension、FormExtension 等,在其生命周期方法中注册观察者,处理配置变化。

在 onConfigurationUpdate() 回调方法中订阅或监听系统环境变量的变化(包括语言,颜色模式,屏幕方向等)。

官方文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/subscribe-system-environment-variable-changes

更多关于HarmonyOS鸿蒙Next中通过订阅系统环境变量变化的几种方式怎么获取设备横竖屏的状态变化通知?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中获取设备横竖屏状态变化通知,可通过以下方式:

  1. 使用ohos.app.ability.Configuration类订阅配置变化:
import common from '@ohos.app.ability.common';

context.configuration.on('change', (config) => {
  if (config.direction === common.Configuration.Direction.VERTICAL) {
    // 竖屏
  } else if (config.direction === common.Configuration.Direction.HORIZONTAL) {
    // 横屏
  }
});
  1. 通过ohos.window模块监听窗口变化:
import window from '@ohos.window';

window.on('orientationChange', (orientation) => {
  if (orientation === window.Orientation.VERTICAL) {
    // 竖屏
  } else if (orientation === window.Orientation.HORIZONTAL) {
    // 横屏
  }
});

在HarmonyOS Next中,可以通过以下方式获取设备横竖屏状态变化通知:

  1. 使用窗口管理器监听:
import window from '@ohos.window';

// 获取窗口对象
let windowClass = await window.getLastWindow(this.context);

// 订阅窗口大小变化事件
windowClass.on('windowSizeChange', (data) => {
  if (data.width > data.height) {
    console.log('横屏状态');
  } else {
    console.log('竖屏状态');
  }
});
  1. 使用屏幕管理器监听:
import screen from '@ohos.screen';

// 获取默认屏幕
let defaultScreen = screen.getDefaultDisplaySync();

// 监听屏幕变化
defaultScreen.on('change', () => {
  let orientation = defaultScreen.orientation;
  if (orientation === screen.Orientation.LANDSCAPE) {
    console.log('横屏状态');
  } else if (orientation === screen.Orientation.PORTRAIT) {
    console.log('竖屏状态');
  }
});
  1. 使用配置变化监听(适用于Ability):
import common from '@ohos.app.ability.common';

export default class MainAbility extends Ability {
  onConfigurationUpdate(config: common.Configuration) {
    if (config.direction === common.Configuration.DIRECTION_HORIZONTAL) {
      console.log('横屏状态');
    } else if (config.direction === common.Configuration.DIRECTION_VERTICAL) {
      console.log('竖屏状态');
    }
  }
}

注意:需要在module.json5中配置相应的权限和事件监听声明。

回到顶部