HarmonyOS @system.brightness \(屏幕亮度\) 不能使用,APP无法运行?

使用了

import brightness, { BrightnessModeResponse, BrightnessResponse } from '@system.brightness' 

获取和设置屏幕亮度,APP无法运行。

阅读 636
1 个回答

@system.brightness接口已经弃用,可通过窗口获取和设置屏幕亮度。获取屏幕亮度:

let winProp = window.getWindowProperties() 
let brightness = winProp.brightness 

设置屏幕亮度:

window.setWindowBrightness 

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-window-V5\#setwindowbrightness9

可以参考下述demo:

import window from '@ohos.window';
import { BusinessError } from '@ohos.base';
import promptAction from '@ohos.promptAction';

@Entry
@Component
struct Index {
  @State currentScreenBrightness: number = 0;
  @State clickCount: number = 0;
  @State baseBrightness: number = 0.1;
  @State operation: string = 'increase';

  /**
   * 设置应用内屏幕亮度
   */
  setScreenBrightness(brightness: number) {
    window.getLastWindow(getContext(this)).then(currentWindow => {
      currentWindow.setWindowBrightness(brightness, (err: BusinessError) => {
        const errCode: number = err.code;
        if (errCode) {
          console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err));
          return;
        }
        console.info('Succeeded in setting the brightness.');
      });
    });
  }

  /**
   * 获取应用内屏幕亮度
   */
  getScreenBrightness() {
    window.getLastWindow(getContext(this)).then(currentWindow => {
      let properties = currentWindow.getWindowProperties();
      this.currentScreenBrightness = properties.brightness;
      console.info(`properties:${JSON.stringify(properties)}`)
    });
  }

  build() {
    Column() {
      Text(`current screen brightness: ${this.currentScreenBrightness}`)
      Button(`click to ${this.operation} brightness`)
        .onClick(() => {
          if (this.operation === 'increase') {
            this.clickCount++;
            if (this.baseBrightness * this.clickCount <= 1.0) {
              this.setScreenBrightness(this.baseBrightness * this.clickCount);
            } else {
              promptAction.showToast({
                message: '亮度值已达到上限!'
              })
              this.operation = 'decrease';
            }
          } else if (this.operation === 'decrease') {
            this.clickCount--;
            if (this.baseBrightness * this.clickCount >= 0.0) {
              this.setScreenBrightness(this.baseBrightness * this.clickCount);
            } else {
              promptAction.showToast({
                message: '亮度值已达到下限!'
              })
              this.operation = 'increase';
            }
          }

        })
        .margin({
          top: 20,
          bottom: 20
        })
      Button('click to get brightness')
        .onClick(() => {
          this.getScreenBrightness();
        })
        .margin({
          bottom: 20
        })
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进