We use essential cookies for the website to function, as well as analytics cookies for analyzing and creating statistics of the website performance. To agree to the use of analytics cookies, click "Accept All". You can manage your preferences at any time by clicking "Cookie Settings" on the footer. More Information.

Only Essential Cookies
Accept All

Controlling Brightness and Always-On (ArkTS)

When to Use

Brightness control is used to adjust the display brightness of an app window or device screen. You can dynamically adjust brightness based on page content characteristics, usage scenarios, and display requirements to improve page readability and content legibility. Brightness mainly includes window brightness and display brightness.

Always-on control is used to determine whether the screen remains lit for a period of time. It is suitable for scenarios that require continuous content display or long-term interactive visibility, preventing the system's automatic screen-off from affecting business processes.

Window Brightness and Display Brightness

  • Window brightness: Refers to the display brightness of the current app window. It only applies to the main window and does not directly modify the device's global brightness.

    You can adjust the window brightness individually based on the display requirements of the current page to optimize the display effect within the app. The window brightness of the main window can be set by calling the setWindowBrightness() API.

    NOTE

    When using the setWindowBrightness() API to set the window brightness of the main window:

    • When the main window is in the foreground and has focus, the window brightness takes effect (that is, the set brightness value becomes the actual display brightness of the current window). It only affects the brightness of the current device screen and cannot modify the screen brightness of virtual screens (such as the screen where the device is being cast).

    • When the window moves to the background, the window brightness becomes invalid and can be adjusted through the control center or shortcut keys. It is not recommended to call this API consecutively or when the window has moved to the background, as this may cause timing issues.

  • Display brightness: Refers to the global display brightness of the device screen. Its scope covers the entire screen and affects the display effect of the system UI and all app windows.

    Display brightness can be adjusted through the Control Center or Settings > Display & brightness. There is currently no API for directly setting the system display brightness, but when -1 is passed to setWindowBrightness(), the window brightness is restored to the system display brightness.

Controlling Screen Always-On

Controlling screen always-on refers to calling the setWindowKeepScreenOn() API to set whether the device screen remains always-on when the current window is in the foreground. When a window set to always-on exists in the foreground, the device's automatic screen-off timeout capability will be disabled. This does not take effect on heterogenous virtual screens.

It is recommended to use this in scenarios where it is clear and necessary to keep the screen always-on, such as navigation, video playback, drawing, and gaming. In scenarios without screen interaction, pure audio playback, or other situations where the screen does not need to stay on continuously, setting screen always-on is not recommended.

When the window moves to the background, the system automatically releases the always-on lock held by that window. For video playback apps, when the audio or video stream is interrupted for a period of time, such as during pausing or network buffering, the system will also automatically release the always-on lock.

NOTE

Keeping the screen always-on for extended periods in such scenarios may increase device power consumption and affect battery life. It is recommended to reasonably control the always-on duration based on the service requirements to ensure user experience.

The sample code is as follows:

Collapse
Word wrap
Dark theme
Copy code
  1. import { window } from '@kit.ArkUI';
  2. import { common } from '@kit.AbilityKit';
  3. import { hilog } from '@kit.PerformanceAnalysisKit';
  4. const DOMAIN = 0x0000;
  5. @Entry
  6. @Component
  7. struct Index {
  8. @State brightnessValue: number = 0.5;
  9. @State keepScreenOn: boolean = false;
  10. @State statusText: string = 'Adjust window brightness or keep-screen-on.';
  11. private currentWindow?: window.Window = undefined;
  12. aboutToAppear(): void {
  13. void this.initWindow();
  14. }
  15. // Get the current app window, and then set the window brightness and always‑on state through the Window object.
  16. private async initWindow(): Promise<void> {
  17. try {
  18. const hostContext = this.getUIContext().getHostContext();
  19. if (!hostContext) {
  20. throw new Error('Host context is unavailable.');
  21. }
  22. const context = hostContext as common.UIAbilityContext;
  23. this.currentWindow = await window.getLastWindow(context);
  24. const windowId = this.currentWindow.getWindowProperties().id;
  25. this.statusText = `window ready, id=${windowId}`;
  26. hilog.info(DOMAIN, 'windowBrightness', this.statusText);
  27. } catch (err) {
  28. this.statusText = `initWindow failed: ${JSON.stringify(err)}`;
  29. hilog.error(DOMAIN, 'windowBrightness', this.statusText);
  30. }
  31. }
  32. // Ensure the window object is initialized before calling the API.
  33. private async ensureWindow(): Promise<boolean> {
  34. if (!this.currentWindow) {
  35. await this.initWindow();
  36. }
  37. if (!this.currentWindow) {
  38. this.statusText = 'current window is unavailable.';
  39. return false;
  40. }
  41. return true;
  42. }
  43. // Set the current window brightness. The value ranges from 0 to 1. Passing -1 restores the system display brightness.
  44. private async applyBrightness(): Promise<void> {
  45. if (!await this.ensureWindow()) {
  46. return;
  47. }
  48. try {
  49. await this.currentWindow!.setWindowBrightness(this.brightnessValue);
  50. this.statusText = `setWindowBrightness(${this.brightnessValue.toFixed(2)}) success`;
  51. hilog.info(DOMAIN, 'windowBrightness', this.statusText);
  52. } catch (err) {
  53. this.statusText = `setWindowBrightness failed: ${JSON.stringify(err)}`;
  54. hilog.error(DOMAIN, 'windowBrightness', this.statusText);
  55. }
  56. }
  57. // Set whether to keep the screen on when the current window is in the foreground.
  58. private async applyKeepScreenOn(value: boolean): Promise<void> {
  59. if (!await this.ensureWindow()) {
  60. return;
  61. }
  62. try {
  63. this.keepScreenOn = value;
  64. await this.currentWindow!.setWindowKeepScreenOn(value);
  65. this.statusText = `setWindowKeepScreenOn(${value}) success`;
  66. hilog.info(DOMAIN, 'windowBrightness', this.statusText);
  67. } catch (err) {
  68. this.statusText = `setWindowKeepScreenOn failed: ${JSON.stringify(err)}`;
  69. hilog.error(DOMAIN, 'windowBrightness', this.statusText);
  70. }
  71. }
  72. build() {
  73. Column({ space: 16 }) {
  74. Text('Brightness and Keep Screen On')
  75. .fontSize(24)
  76. .fontWeight(FontWeight.Bold)
  77. .width('100%')
  78. .textAlign(TextAlign.Start)
  79. Text(`Brightness: ${this.brightnessValue.toFixed(2)}`)
  80. .width('100%')
  81. .fontSize(16)
  82. .textAlign(TextAlign.Start)
  83. Slider({
  84. value: this.brightnessValue,
  85. min: 0,
  86. max: 1,
  87. step: 0.01
  88. })
  89. .width('100%')
  90. .showTips(true)
  91. .onChange((value: number) => {
  92. this.brightnessValue = value;
  93. })
  94. Button('Apply Brightness')
  95. .width('100%')
  96. .onClick(() => {
  97. void this.applyBrightness();
  98. })
  99. Row() {
  100. Text(`Keep screen on: ${this.keepScreenOn}`)
  101. .layoutWeight(1)
  102. .fontSize(16)
  103. Toggle({ type: ToggleType.Switch, isOn: this.keepScreenOn })
  104. .onChange((value: boolean) => {
  105. void this.applyKeepScreenOn(value);
  106. })
  107. }
  108. .width('100%')
  109. Text(this.statusText)
  110. .width('100%')
  111. .fontSize(14)
  112. .textAlign(TextAlign.Start)
  113. }
  114. .width('100%')
  115. .height('100%')
  116. .padding(20)
  117. .alignItems(HorizontalAlign.Start)
  118. }
  119. }
Search in Guides
Enter a keyword.