1# Window Management Development
2
3
4## How do I obtain the height of the status bar and navigation bar? (API version 9)
5
6**Solution**
7
8Before the window content is loaded, enable listening for the **systemAvoidAreaChange** event.
9
10**Example**
11
12```
13// MainAbility.ts
14import window from '@ohos.window';
15
16/**
17 * Set the immersive window and obtain the height of the status bar and navigation bar.
18 * @param mainWindow Indicates the main window.
19 */
20async function enterImmersion(mainWindow: window.Window) {
21  window.on("systemBarTintChange", (data) => {
22    let avoidAreaRect = data.regionTint[0].region; // data.regionTint is an array that contains the rectangle coordinates of the status bar and navigation bar.
23  })
24  await mainWindow.setFullScreen(true)
25  await mainWindow.setSystemBarEnable(["status", "navigation"])
26  await mainWindow.systemBarProperties({
27    navigationBarColor: "#00000000",
28    statusBarColor: "#00000000",
29    navigationBarContentColor: "#FF0000",
30    statusBarContentColor: "#FF0000"
31  })
32}
33export default class MainAbility extends Ability {
34  // Do something.
35  async onWindowStageCreate(windowStage: window.WindowStage) {
36    let mainWindow = await windowStage.getMainWindow()
37    await enterImmersion(mainWindow)
38    windowStage.loadContent('pages/index')
39  }
40  // Do something.
41}
42```
43
44
45## How do I hide the status bar on the top of an application? (API version 9)
46
47**Solution**
48
49Use **setWindowSystemBarEnable** in the **onWindowStageCreate** lifecycle callback of UIAbility.
50
51**Example**
52
53```
54onWindowStageCreate(windowStage){
55  windowStage.getMainWindowSync().setWindowSystemBarEnable([])
56  ......
57}
58```
59
60**References**
61
62[Window](../reference/apis-arkui/js-apis-window.md)
63
64## How do I lock the window in portrait mode so that it does not rotate with the device? (API version 9)
65
66Applicable to: stage model
67
68**Solution**
69
70To lock the window in portrait mode, call **setPreferredOrientation** of the window module, with **orientation** set to **window.Orientation.PORTRAIT**.
71
72**Example**
73
74```
75import window from "@ohos.window";
76// 1. Obtain a Window instance. Specifically, you can call createWindow to create a window or findWindow to obtain an existing window.
77let windowClass = null;
78let config = {name: "alertWindow", windowType: window.WindowType.TYPE_SYSTEM_ALERT, ctx: this.context};
79try {
80    let promise = window.createWindow(config);
81    promise.then((data)=> {
82        windowClass = data;
83        console.info('Succeeded in creating the window. Data:' + JSON.stringify(data));
84    }).catch((err)=>{
85        console.error('Failed to create the Window. Cause:' + JSON.stringify(err));
86    });} catch (exception) {
87    console.error('Failed to create the window. Cause: ' + JSON.stringify(exception));
88}
89// 2. Call setPreferredOrientation to set the window orientation. The value PORTRAIT indicates that the window is displayed in portrait mode.
90let orientation = window.Orientation.PORTRAIT;
91if (windowClass) {
92    windowClass.setPreferredOrientation(orientation, (err) => {
93        if (err.code) {
94            console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err));
95            return;
96        }
97        console.info('Succeeded in setting window orientation.');
98}
99```
100
101**References**
102
103[window.Orientation](../reference/apis-arkui/js-apis-window.md#orientation9)
104
105## Why do the isStatusBarLightIcon and isNavigationBarLightIcon attributes set by calling setWindowSystemBarProperties not take effect? (API version 9)
106
107Applicable to: stage model
108
109**Solution**
110
111In effect, the **isStatusBarLightIcon** and **isNavigationBarLightIcon** attributes turn the font white when set to **true**. If **statusBarContentColor** is also set in **setWindowSystemBarProperties**, the **isStatusBarLightIcon** attribute does not take effect. Similarly, if **navigationBarContentColor** is set, the **isNavigationBarLightIcon** attribute does not take effect.
112
113**References**
114
115[window.SystemBarProperties](../reference/apis-arkui/js-apis-window.md#systembarproperties)
116
117
118## How do I keep the device screen always on? (API version 9)
119
120**Solution**
121
122Obtain a **Window** instance, and call [setWindowKeepScreenOn](../reference/apis-arkui/js-apis-window.md#setwindowkeepscreenon9) to keep the device screen always on.
123
124**Example**
125
126```
127let isKeepScreenOn = true;
128try {
129    windowClass.setWindowKeepScreenOn(isKeepScreenOn, (err) => {
130        if (err.code) {
131            console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err));
132            return;
133        }
134        console.info('Succeeded in setting the screen to be always on.');
135    });
136} catch (exception) {
137    console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(exception));
138}
139```
140
141
142## How do I listen for window size changes? (API version 9)
143
144After obtaining a **Window** instance, you can call [window.on('windowSizeChange')](../reference/apis-arkui/js-apis-window.md#onwindowsizechange7) to listen for window size changes.
145
146Note that this event is not triggered if the window size does not change. For example, if the window is rotated by 180 degrees without any size change, the callback is not invoked. In this case, listen for the [display.on('change')](../reference/apis-arkui/js-apis-display.md#displayonaddremovechange) event and obtain the window size through the **display** interface within the callback.
147
148```
149try {
150    windowClass.on('windowSizeChange', (data) => {
151        console.info('Succeeded in enabling the listener for window size changes. Data: ' + JSON.stringify(data));
152   });
153} catch (exception) {
154    console.error('Failed to enable the listener for window size changes. Cause: ' + JSON.stringify(exception));
155}
156```
157
158## How do I listen for orientation status changes of the device screen? (API version 10)
159
160**Solution**
161
162Use **display.on** to listen for the orientation status changes.
163
164**References**
165
166[Subscribing to Display Changes](../reference/apis-arkui/js-apis-display.md#displayonaddremovechange)
167
168## How do I enable the window to rotate with the device? (API version 10)
169
170**Solution**
171
172- Abilty-level configuration: Set **EntryAbility** to **orientation** in the **module.json5** file.
173- Dynamic setting: Use **window.setPreferredOrientation** to set the window orientation.
174
175**Example**
176```ts
177import window from '@ohos.window';
178import display from '@ohos.display';
179
180const TAG = 'foo'
181const ORIENTATION: Array<string> = ['Portrait', 'Landscape','Reverse portrait','Reverse landscape']
182
183@Entry
184@Component
185struct ScreenTest {
186  @State rotation: number = 0
187  @State message: string = ORIENTATION[this.rotation]
188
189  aboutToAppear() {
190    this.setOrientation()
191
192    let callback = async () => {
193      let d = await display.getDefaultDisplaySync()
194      this.rotation = d.rotation
195      this.message = ORIENTATION[this.rotation]
196      console.info(TAG, JSON.stringify(d))
197    }
198    try {
199      display.on("change", callback); // Listen for device screen status changes.
200    } catch (exception) {
201      console.error(TAG, 'Failed to register callback. Code: ' + JSON.stringify(exception));
202    }
203  }
204
205  setOrientation() {
206    try {
207      window.getLastWindow(getContext(this), (err, data) => { // Obtain a Window instance.
208        if (err.code) {
209          console.error(TAG, 'Failed to obtain the top window. Cause: ' + JSON.stringify(err));
210          return;
211        }
212        let windowClass = data;
213        console.info(TAG, 'Succeeded in obtaining the top window. Data: ' + JSON.stringify(data));
214
215        let orientation = window.Orientation.AUTO_ROTATION; // Set the window orientation to AUTO_ROTATION.
216        try {
217          windowClass.setPreferredOrientation(orientation, (err) => {
218            if (err.code) {
219              console.error(TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(err));
220              return;
221            }
222            console.info(TAG, 'Succeeded in setting window orientation.');
223          });
224        } catch (exception) {
225          console.error(TAG, 'Failed to set window orientation. Cause: ' + JSON.stringify(exception));
226        }
227        ;
228      });
229    } catch (exception) {
230      console.error(TAG, 'Failed to obtain the top window. Cause: ' + JSON.stringify(exception));
231    }
232    ;
233  }
234
235  build() {
236    Row() {
237      Column() {
238        Text(`${this.rotation}`).fontSize(25)
239        Text(`${this.message}`).fontSize(25)
240      }
241      .width("100%")
242    }
243    .height("100%")
244  }
245}
246```
247**References**
248
249[Setting the Window Orientation](../reference/apis-arkui/js-apis-window.md#setpreferredorientation9)
250
251[Subscribing to Display Changes](../reference/apis-arkui/js-apis-display.md#displayonaddremovechange)
252
253## Why a window instance cannot be used to obtain the updated window size in the display.on('change') callback? (API version 10)
254
255**Solution**
256
257The rotation action involves two modules, [@ohos.window](../reference/apis-arkui/js-apis-window.md) and [@ohos.display](../reference/apis-arkui/js-apis-display.md), which are running in separate processes. The sequence of updates following a rotation results in a temporal discrepancy: the display module updates by simply swapping width and height values, whereas the window module requires the completion of the ArkUI layout to determine the window size, which is a more time-consuming process. Consequently, attempting to retrieve the window information via the **Window** instance within the display change event will reflect outdated dimensions. As such, applications should register for the **display.on('change')** event and obtain screen dimensions such as width, height, and orientation from the **Display** instance within the callback.
258
259**Example (incorrect)**
260
261```ts
262// The display module updates first.
263display.on('change', async (data) => {
264  let newDisplay: display.Display = display.getDefaultDisplaySync();
265  console.info('Orientation: ' + newDisplay.orientation);
266  let windowClass: window.Window = await window.getLastWindow(this.context);
267  // The window module updates later. The original width and height are obtained.
268  let windowProperties = windowClass.getWindowProperties();
269  console.info('Width: ' + windowProperties.windowRect.width +
270    ', height: ' + windowProperties.windowRect.height);
271  // Ensure that the related Window instance, that is, windowClass, has been obtained.
272  windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_CUTOUT);
273});
274```
275
276**Correct example**
277
278```ts
279display.on('change', (data) => {
280  console.info('Succeeded in enabling the listener for display changes. Data: ' +
281  JSON.stringify(data));
282  let newDisplay: display.Display = display.getDefaultDisplaySync();
283  console.info('Orientation: ' + newDisplay.orientation + 'width: ' +
284  newDisplay.width + ', height: ' + newDisplay.height);
285});
286```
287
288**References**
289
290[display.on('change')](../reference/apis-arkui/js-apis-display.md#displayonaddremovechange)
291
292## How do I obtain the screen orientation and avoidAreaChange information at the same time? (API version 10)
293
294You can use [on('avoidAreaChange')](../reference/apis-arkui/js-apis-window.md#onavoidareachange9) to listen for avoidance area changes and obtain **avoidAreaChange** from the callback. You can obtain the screen orientation information through the **Display** instance.
295
296```ts
297// Ensure that the related Window instance, that is, windowClass, has been obtained.
298windowClass.on('avoidAreaChange', async (data) => {
299  console.info('Succeeded in enabling the listener for avoid area changes. Type: ' +
300    JSON.stringify(data.type) + ', area ' + JSON.stringify(data.area));
301  let newDisplay: display.Display = display.getDefaultDisplaySync();
302  console.info('Orientation: ' + newDisplay.orientation);
303  let windowClass: window.Window = await window.getLastWindow(this.context);
304  windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_CUTOUT);
305});
306```
307
308<!--no_check-->
309