HarmonyOS 应用亮度获取第一次值错误,为-1

this.windowClass = await window.getLastWindow(getContext(this))
this.oriBrightness = this.windowClass.getWindowProperties().brightness

这个亮度,自己没有设置之前,获取到是-1,系统明明有亮度值的,这块不正确,我看了一下文档,说跟随系统亮度值获取不是这个方法,那是哪个方法呢?

HarmonyOS
15h前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
fox280

可以参考如下demo获取跟随系统的亮度数值以及设置窗口亮度后如何获取当前窗口亮度:

import { promptAction, router, window } from '@kit.ArkUI';
import settings from '@ohos.settings';
import { BusinessError } from '@ohos.base';


@Entry
@Component
export struct Index {


  @State windowClass: window.Window | undefined = undefined;

  /**
   * 获取跟随系统的亮度数值
   */
  getLightWithoutSetting(){
    let context = getContext(this);
    let value = settings.getValueSync(context, settings.display.SCREEN_BRIGHTNESS_STATUS, '10');
    console.log(`当前屏幕的亮度为: ${JSON.stringify(value)}`);


  }

  /**
   * 只有设置窗口亮度后再获取,亮度信息才不会是-1
   */
  getLight() {
    let brightness: number = 0.78;
    let windowStage: window.WindowStage | undefined = AppStorage.get('windowStage') as window.WindowStage
    windowStage.getMainWindow((err: BusinessError, data) => {
      const errCode: number = err.code;
      if (errCode) {
        console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(err));
        return;
      }
      this.windowClass = data;
      this.windowClass.setWindowBrightness(brightness, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err));
          return;
        }

        let screenLight = this.windowClass?.getWindowProperties().brightness
        console.info('Succeeded in setting the brightness.');
        console.info(`Succeeded in getting the light:${screenLight}`);
      });

    });
  }


  build() {
    Column({ space: 10 }) {

      Button('获取亮度').onClick(() => {
        this.getLightWithoutSetting()
      })

      Button('点击设置并获取亮度')
        .onClick(() => {
          this.getLight()
        })

    }.width('100%')
    .height("100%")
    .justifyContent(FlexAlign.Center)
  }
}

运行上述代码前需替换EntryAbility.ets文件中的onWindowStageCreate方法

//替换代码如下:
onWindowStageCreate(windowStage: window.WindowStage): void {

  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

  windowStage.loadContent('pages/Index', (err) => {
  AppStorage.setOrCreate('windowStage',windowStage)
  if (err.code) {
  hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  return;
}
hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
});
}
分享
微博
QQ
微信
回复
12h前
相关问题
如何判断APP是否是第一次请求权限?
383浏览 • 1回复 待解决
获取和设置应用内屏幕亮度
1086浏览 • 1回复 待解决
获取系统的屏幕亮度
519浏览 • 1回复 待解决
HarmonyOS 怎么获取当前屏幕亮度
35浏览 • 1回复 待解决
HarmonyOS 每秒执行一次的函数
193浏览 • 2回复 待解决