1# 管理系统窗口(仅Stage模型支持)
2
3## 管理系统窗口概述
4
5在`Stage`模型下, 允许系统应用创建和管理系统窗口,包括音量条、壁纸、通知栏、状态栏、导航栏等。具体支持的系统窗口类型见[API参考-WindowType](../reference/apis-arkui/js-apis-window.md#windowtype7)。
6
7在窗口显示、隐藏及窗口间切换时,窗口模块通常会添加动画效果,以使各个交互过程更加连贯流畅。
8
9在OpenHarmony中,应用窗口的动效为默认行为,不需要开发者进行设置或者修改。
10
11相对于应用窗口,在显示系统窗口过程中,开发者可以自定义窗口的显示动画、隐藏动画。
12
13> **说明:**
14>
15> 本文档涉及系统接口的使用,请使用full-SDK进行开发。<!--Del-->具体使用可见[full-SDK替换指南](../faqs/full-sdk-switch-guide.md)。<!--DelEnd-->
16
17
18## 接口说明
19
20更多API说明请参见[API参考](../reference/apis-arkui/js-apis-window-sys.md)。
21
22| 实例名            | 接口名                                                       | 描述                                                         |
23| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
24| window静态方法    | createWindow(config: Configuration, callback: AsyncCallback\<Window>): void | 创建子窗口或系统窗口。<br/>-`config`:创建窗口时的参数。     |
25| Window            | resize(width: number, height: number, callback: AsyncCallback&lt;void&gt;): void | 改变当前窗口大小。                                           |
26| Window            | moveWindowTo(x: number, y: number, callback: AsyncCallback&lt;void&gt;): void | 移动当前窗口位置。                                           |
27| Window            | setUIContent(path: string, callback: AsyncCallback&lt;void&gt;): void | 根据当前工程中某个页面的路径为窗口加载具体的页面内容。<br>其中path为要加载到窗口中的页面内容的路径,在Stage模型下该路径需添加到工程的main_pages.json文件中。                                     |
28| Window            | showWindow(callback: AsyncCallback\<void>): void             | 显示当前窗口。                                               |
29| Window            | on(type: 'touchOutside', callback: Callback&lt;void&gt;): void | 开启本窗口区域外的点击事件的监听。                           |
30| Window            | hide (callback: AsyncCallback\<void>): void                  | 隐藏当前窗口。此接口为系统接口。                             |
31| Window            | destroyWindow(callback: AsyncCallback&lt;void&gt;): void     | 销毁当前窗口。                                               |
32| Window            | getTransitionController(): TransitionController              | 获取窗口属性转换控制器。此接口为系统接口。                   |
33| TransitionContext | completeTransition(isCompleted: boolean): void               | 设置属性转换的最终完成状态。该函数需要在动画函数[animateTo()](../reference/apis-arkui/arkui-ts/ts-explicit-animation.md)执行后设置。此接口为系统接口。 |
34| Window            | showWithAnimation(callback: AsyncCallback\<void>): void      | 显示当前窗口,过程中播放动画。此接口为系统接口。             |
35| Window            | hideWithAnimation(callback: AsyncCallback\<void>): void      | 隐藏当前窗口,过程中播放动画。此接口为系统接口。             |
36
37## 系统窗口的开发
38
39本文以音量条窗口为例,介绍系统窗口的基本开发和管理步骤。
40
41### 开发步骤
42
43
441. 创建系统窗口。
45
46   在[ServiceExtensionContext](../reference/apis-ability-kit/js-apis-inner-application-serviceExtensionContext-sys.md)下,使用`window.createWindow`接口创建音量条系统窗口。
47
482. 操作或设置系统窗口的属性。
49
50   系统窗口创建成功后,可以改变其大小、位置等,还可以根据需要设置系统窗口的背景色、亮度等属性。
51
523. 加载显示系统窗口的具体内容。
53
54   通过`setUIContent`和`showWindow`接口加载显示音量条窗口的具体内容。
55
564. 隐藏/销毁系统窗口。
57
58   当不再需要音量条窗口时,可根据具体实现逻辑,使用`hide`接口或`destroyWindow`接口对其进行隐藏或销毁。
59
60```ts
61import { Want, ServiceExtensionAbility } from '@kit.AbilityKit';
62import { window } from '@kit.ArkUI';
63import { BusinessError } from '@kit.BasicServicesKit';
64
65export default class ServiceExtensionAbility1 extends ServiceExtensionAbility {
66  onCreate(want: Want) {
67    // 1.创建音量条窗口。
68    let windowClass: window.Window | null = null;
69    let config: window.Configuration = {
70      name: "volume", windowType: window.WindowType.TYPE_VOLUME_OVERLAY, ctx: this.context
71    };
72    window.createWindow(config, (err: BusinessError, data) => {
73      let errCode: number = err.code;
74      if (errCode) {
75        console.error('Failed to create the volume window. Cause:' + JSON.stringify(err));
76        return;
77      }
78      console.info('Succeeded in creating the volume window.')
79      windowClass = data;
80      // 2.创建音量条窗口成功之后,可以改变其大小、位置或设置背景色、亮度等属性。
81      windowClass.moveWindowTo(300, 300, (err: BusinessError) => {
82        let errCode: number = err.code;
83        if (errCode) {
84          console.error('Failed to move the window. Cause:' + JSON.stringify(err));
85          return;
86        }
87        console.info('Succeeded in moving the window.');
88      });
89      windowClass.resize(500, 500, (err: BusinessError) => {
90        let errCode: number = err.code;
91        if (errCode) {
92          console.error('Failed to change the window size. Cause:' + JSON.stringify(err));
93          return;
94        }
95        console.info('Succeeded in changing the window size.');
96      });
97      // 3.为音量条窗口加载对应的目标页面。
98      windowClass.setUIContent("pages/page_volume", (err: BusinessError) => {
99        let errCode: number = err.code;
100        if (errCode) {
101          console.error('Failed to load the content. Cause:' + JSON.stringify(err));
102          return;
103        }
104        console.info('Succeeded in loading the content.');
105        // 3.显示音量条窗口。
106        (windowClass as window.Window).showWindow((err: BusinessError) => {
107          let errCode: number = err.code;
108          if (errCode) {
109            console.error('Failed to show the window. Cause:' + JSON.stringify(err));
110            return;
111          }
112          console.info('Succeeded in showing the window.');
113        });
114      });
115      // 4.隐藏/销毁音量条窗口。当不再需要音量条时,可根据具体实现逻辑,对其进行隐藏或销毁。
116      // 此处以监听音量条区域外的点击事件为例实现音量条窗口的隐藏。
117      windowClass.on('touchOutside', () => {
118        console.info('touch outside');
119        (windowClass as window.Window).hide((err: BusinessError) => {
120          let errCode: number = err.code;
121          if (errCode) {
122            console.error('Failed to hide the window. Cause: ' + JSON.stringify(err));
123            return;
124          }
125          console.info('Succeeded in hiding the window.');
126        });
127      });
128    });
129  }
130};
131```
132
133## 自定义系统窗口的显示与隐藏动画
134
135在显示系统窗口过程中,开发者可以自定义窗口的显示动画。在隐藏系统窗口过程中,开发者可以自定义窗口的隐藏动画。本文以显示和隐藏动画为例介绍主要开发步骤。
136
137### 开发步骤
138
1391. 获取窗口属性转换控制器。
140
141   通过`getTransitionController`接口获取控制器。后续的动画操作都由属性控制器来完成。
142
1432. 配置窗口显示时的动画。
144
145   通过动画函数[animateTo()](../reference/apis-arkui/arkui-ts/ts-explicit-animation.md)配置具体的属性动画。
146
1473. 设置属性转换完成。
148
149   通过`completeTransition(true)`来设置属性转换的最终完成状态。如果传入false,则表示撤销本次转换。
150
1514. 显示或隐藏当前窗口,过程中播放动画。
152
153   调用`showWithAnimation`接口,来显示窗口并播放动画。调用`hideWithAnimation`接口,来隐藏窗口并播放动画。
154
155```ts
156// xxx.ts 实现使用ts文件引入showWithAnimation,hideWithAnimation方法
157import { window } from '@kit.ArkUI';
158
159export class AnimationConfig {
160  private animationForShownCallFunc_: Function = undefined;
161  private animationForHiddenCallFunc_: Function = undefined;
162
163  ShowWindowWithCustomAnimation(windowClass: window.Window, callback) {
164    if (!windowClass) {
165      console.error('LOCAL-TEST windowClass is undefined');
166      return false;
167    }
168    this.animationForShownCallFunc_ = callback;
169    // 获取窗口属性转换控制器
170    let controller: window.TransitionController = windowClass.getTransitionController();
171    controller.animationForShown = (context: window.TransitionContext)=> {
172      this.animationForShownCallFunc_(context);
173    };
174
175    windowClass.showWithAnimation(()=>{
176      console.info('LOCAL-TEST show with animation success');
177    })
178    return true;
179  }
180
181  HideWindowWithCustomAnimation(windowClass: window.Window, callback) {
182    if (!windowClass) {
183      console.error('LOCAL-TEST window is undefined');
184      return false;
185    }
186    this.animationForHiddenCallFunc_ = callback;
187    // 获取窗口属性转换控制器
188    let controller: window.TransitionController = windowClass.getTransitionController();
189    controller.animationForHidden = (context : window.TransitionContext) => {
190      this.animationForHiddenCallFunc_(context);
191    };
192
193    windowClass.hideWithAnimation(()=>{
194      console.info('Hide with animation success');
195    })
196    return true;
197  }
198}
199```
200
201```ts
202// xxx.ets 实现主窗口创建相关操作
203import { window } from '@kit.ArkUI';
204import { UIAbility, Want, AbilityConstant, common } from '@kit.AbilityKit';
205import { hilog } from '@kit.PerformanceAnalysisKit'
206
207export default class EntryAbility extends UIAbility {
208  onCreate(want: Want,launchParam:AbilityConstant.LaunchParam) {
209    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
210  }
211
212  onDestroy(): void {
213    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability Destroy');
214  }
215
216  onWindowStageCreate(windowStage:window.WindowStage): void{
217    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
218
219    windowStage.loadContent('pages/transferControllerPage',(err, data)=>{
220      if(err.code){
221        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause:%{public}s', JSON.stringify(err)??'');
222        return ;
223      }
224      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data:%{public}s', JSON.stringify(data)??'');
225
226    });
227
228    AppStorage.setOrCreate<common.UIAbilityContext>("currentContext",this.context);
229  }
230
231  onWindowStageDestroy(): void{
232    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
233  }
234
235  onForeground(): void{
236    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
237  }
238
239  onBackground(): void{
240    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
241  }
242};
243```
244
245```ts
246// xxx.ets 实现子窗口的属性设置
247import { window, router } from '@kit.ArkUI';
248import { common } from '@kit.AbilityKit';
249
250@Entry
251@Component
252struct transferCtrlSubWindow {
253  @State message: string = 'transferCtrlSubWindow'
254
255  build() {
256    Column() {
257      Text("close")
258        .fontSize(24)
259        .fontWeight(FontWeight.Normal)
260        .margin({ left: 10, top: 10 })
261      Button() {
262        Text("close")
263          .fontSize(24)
264          .fontSize(FontWeight.Normal)
265      }.width(220).height(68)
266      .margin({ left: 10, top: 10 })
267      .onClick(() => {
268        let subWin = AppStorage.get<window.Window>("TransferSubWindow");
269        subWin?.destroyWindow();
270        AppStorage.setOrCreate<window.Window>("TransferSubWindow", undefined);
271      })
272    }.height('100%').width('100%').backgroundColor('#ff556243').shadow({radius: 30,color: '#ff555555',offsetX: 15,offsetY: 15})
273  }
274}
275```
276
277```ts
278// xxx.ets 实现子窗口的创建以及显示、隐藏窗口时的动效操作
279import { window, router } from '@kit.ArkUI';
280import { common, Want } from '@kit.AbilityKit';
281import { BusinessError } from '@kit.BasicServicesKit';
282import { AnimationConfig } from '../entryability/AnimationConfig';
283
284@Entry
285@Component
286struct Index {
287  @State message: string = 'transferControllerWindow';
288
289  private animationConfig_?:AnimationConfig = undefined;
290  private subWindow_?:window.Window = undefined;
291
292  aboutToAppear(){
293    if(!this.animationConfig_){
294      this.animationConfig_ = new AnimationConfig();
295    }
296  }
297
298  private CreateTransferSubWindow(){
299    if(this.subWindow_){
300      this.subWindow_ = AppStorage.get<window.Window>("TransferSubWindow");
301      if(!this.subWindow_){
302        this.subWindow_ = undefined;
303      }
304    }
305    let context = AppStorage.get<common.UIAbilityContext>("currentContext");
306    console.log('LOCAL-TEST try to CreateTransferSubWindow');
307    let windowConfig:window.Configuration = {
308      name : "systemTypeWindow",
309      windowType : window.WindowType.TYPE_FLOAT,
310      ctx : context,
311    };
312    let promise = window?.createWindow(windowConfig);
313    promise?.then(async(subWin) => {
314      this.subWindow_ = subWin;
315      AppStorage.setOrCreate<window.Window>("systemTypeWindow", subWin);
316      await subWin.setUIContent("pages/transferCtrlSubWindow",()=>{});
317      await subWin.moveWindowTo(100,100);
318      await subWin.resize(200,200);
319    }).catch((err:Error)=>{
320      console.log('LOCAL-TEST createSubWindow err:' + JSON.stringify(err));
321    })
322  }
323  private ShowSUBWindow(){
324    if(!this.subWindow_){
325      console.log('LOCAL-TEST this.subWindow_is null');
326      return ;
327    }
328    let animationConfig = new AnimationConfig();
329    let systemTypeWindow = window.findWindow("systemTypeWindow");
330    console.log("LOCAL-TEST try to ShowWindowWithCustomAnimation");
331    animationConfig.ShowWindowWithCustomAnimation(systemTypeWindow,(context:window.TransitionContext)=>{
332      console.info('LOCAL-TEST start show window animation');
333      let toWindow = context.toWindow;
334      animateTo({
335        duration: 200, // 动画时长
336        tempo: 0.5, // 播放速率
337        curve: Curve.EaseInOut, // 动画曲线
338        delay: 0, // 动画延迟
339        iterations: 1, // 播放次数
340        playMode: PlayMode.Normal, // 动画模式
341        onFinish: () => {
342          console.info('LOCAL-TEST onFinish in show animation');
343          context.completeTransition(true);
344        }
345      },() => {
346        let obj: window.TranslateOptions = {
347          x: 100.0,
348          y: 0.0,
349          z: 0.0
350        };
351        try {
352          toWindow.translate(obj); // 设置动画过程中的属性转换
353        }catch(exception){
354          console.error('Failed to translate. Cause: ' + JSON.stringify(exception));
355        }
356      });
357      console.info('LOCAL-TEST complete transition end');
358    });
359  }
360
361  private HideSUBWindow(){
362    if(!this.subWindow_){
363      console.log('LOCAL-TEST this.subWindow_is null');
364      return ;
365    }
366    let animationConfig = new AnimationConfig();
367    let systemTypeWindow = window.findWindow("systemTypeWindow");
368    console.log("LOCAL-TEST try to HideWindowWithCustomAnimation");
369    animationConfig.HideWindowWithCustomAnimation(systemTypeWindow,(context:window.TransitionContext)=>{
370      console.info('LOCAL-TEST start hide window animation');
371      let toWindow = context.toWindow;
372      animateTo({
373        duration: 200, // 动画时长
374        tempo: 0.5, // 播放速率
375        curve: Curve.EaseInOut, // 动画曲线
376        delay: 0, // 动画延迟
377        iterations: 1, // 播放次数
378        playMode: PlayMode.Normal, // 动画模式
379        onFinish: () => {
380          console.info('LOCAL-TEST onFinish in hide animation');
381          context.completeTransition(true);
382        }
383      },() => {
384        let obj: window.TranslateOptions = {
385          x: 500.0,
386          y: 0.0,
387          z: 0.0
388        };
389        try {
390          toWindow.translate(obj); // 设置动画过程中的属性转换
391        }catch(exception){
392          console.error('Failed to translate. Cause: ' + JSON.stringify(exception));
393        }
394      });
395      console.info('LOCAL-TEST complete transition end');
396    });
397  }
398
399  build() {
400    Column() {
401      Text(this.message)
402        .fontSize(24)
403        .fontWeight(FontWeight.Normal)
404        .margin({left: 10, top: 10})
405
406      Button(){
407        Text("CreateSub")
408          .fontSize(24)
409          .fontWeight(FontWeight.Normal)
410      }.width(220).height(68)
411      .margin({left: 10, top: 10})
412      .onClick(() => {
413        this.CreateTransferSubWindow();
414      })
415
416      Button(){
417        Text("Show")
418          .fontSize(24)
419          .fontWeight(FontWeight.Normal)
420      }.width(220).height(68)
421      .margin({left: 10, top: 10})
422      .onClick(() => {
423        this.ShowSUBWindow();
424      })
425
426      Button(){
427        Text("Hide")
428          .fontSize(24)
429          .fontWeight(FontWeight.Normal)
430      }.width(220).height(68)
431      .margin({left: 10, top: 10})
432      .onClick(() => {
433        this.HideSUBWindow();
434      })
435    }.width('100%').height('100%')
436  }
437}
438```