1/*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16import AbilityConstant from '@ohos.app.ability.AbilityConstant';
17import hilog from '@ohos.hilog';
18import UIAbility from '@ohos.app.ability.UIAbility';
19import Want from '@ohos.app.ability.Want';
20import window from '@ohos.window';
21import hardwareManager from '@ohos.distributedHardware.hardwareManager';
22import { BusinessError } from '@ohos.base';
23import { Configuration } from '@ohos.app.ability.Configuration';
24import screenLock from '@ohos.screenLock';
25
26const TAG = '[testTag_DHardwareUIAbility] : ';
27let systemLanguage: string | undefined;
28
29PersistentStorage.persistProp('camera', 0);
30AppStorage.setOrCreate('camera', 0);
31console.log(TAG + 'OUT : AppStorage.get<number>(camera) : ' + AppStorage.get<number>('camera'));
32
33PersistentStorage.persistProp('mic', 0);
34AppStorage.setOrCreate('mic', 0);
35console.log(TAG + 'OUT : AppStorage.get<number>(mic) : ' + AppStorage.get<number>('mic'));
36
37export default class DHardwareUIAbility extends UIAbility {
38  private isInit: boolean = true;
39  private isStopAbility: boolean = false;
40
41  onConfigurationUpdate(newConfig: Configuration) {
42    console.info(`onConfigurationUpdated systemLanguage is ${systemLanguage}, newConfig: ${JSON.stringify(newConfig)}`);
43
44    if (systemLanguage !== newConfig.language) {
45      console.info(TAG + `systemLanguage from ${systemLanguage} changed to ${newConfig.language}`);
46      systemLanguage = newConfig.language;
47    }
48  }
49
50  stop() {
51    console.info(TAG + 'stop');
52    try {
53      hardwareManager.stopDistributedHardware(AppStorage.get('description') as hardwareManager.HardwareDescriptor)
54        .then(() => {
55          console.log('stop distributed hardware successfully');
56        })
57        .catch((error: BusinessError) => {
58          console.error('stop distributed hardware failed, cause:' + error);
59        })
60      console.log('stop distributed hardware successfully');
61    } catch (error) {
62      console.error('stop distributed hardware failed:' + error);
63    }
64  }
65
66  pause() {
67    console.log(TAG + 'pause');
68    try {
69      hardwareManager.pauseDistributedHardware(AppStorage.get('description') as hardwareManager.HardwareDescriptor)
70        .then(() => {
71          console.log('pause distributed hardware successfully');
72        })
73        .catch((error: BusinessError) => {
74          console.error('pause distributed hardware failed, cause:' + error);
75        })
76      console.log('pause distributed hardware successfully');
77    } catch (error) {
78      console.error('pause distributed hardware failed:' + error);
79    }
80  }
81
82  resume() {
83    console.log(TAG + 'resume');
84    try {
85      hardwareManager.resumeDistributedHardware(AppStorage.get('description') as hardwareManager.HardwareDescriptor)
86        .then(() => {
87          console.log('resume distributed hardware successfully');
88        })
89        .catch((error: BusinessError) => {
90          console.error('resume distributed hardware failed, cause:' + error);
91        })
92      console.log('resume distributed hardware successfully');
93    } catch (error) {
94      console.error('resume distributed hardware failed:' + error);
95    }
96  }
97
98
99  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
100    console.info(TAG + 'onCreate : ' + 'Ability onCreate');
101
102    systemLanguage = this.context.config.language;
103    console.info(TAG + `systemLanguage is ${systemLanguage} `);
104
105    this.isStopAbility = false;
106    console.info(TAG + 'onCreate : ' + 'this.isStopAbility : ' + this.isStopAbility);
107
108    if (want.parameters != undefined) {
109      console.info(TAG + 'onCreate : want.parameters.type : ' + JSON.stringify(want.parameters['type']));
110      console.info(TAG + 'onCreate : want.parameters.srcNetWorkId : ' + JSON.stringify(want.parameters['srcNetWorkId']));
111      console.info(TAG + 'onCreate : want.parameters.deviceName : ' + JSON.stringify(want.parameters['deviceName']));
112      console.info(TAG + 'onCreate : want.parameters.deviceType : ' + JSON.stringify(want.parameters['deviceType']));
113      console.info(TAG + 'onCreate : want.parameters.returnCode : ' + JSON.stringify(want.parameters['returnCode']));
114
115      AppStorage.setOrCreate('type', want.parameters['type']);
116      AppStorage.setOrCreate('srcNetworkId', want.parameters['srcNetworkId']);
117      AppStorage.setOrCreate('deviceName', want.parameters['deviceName']);
118      AppStorage.setOrCreate('deviceType', want.parameters['deviceType']);
119
120      console.log(TAG + 'oncreate : after set want -- type --');
121
122      // startAbility:type+1
123      if (want.parameters['type'] == 1) {
124        let camera: number = AppStorage.get<number>('camera') as number + 1;
125        AppStorage.set('camera', camera);
126        console.log(TAG + 'onCreate : ' + 'AppStorage.get<number>(camera) : ' + AppStorage.get<number>('camera'));
127      } else if (want.parameters['type'] == 1024) {
128        let mic: number = AppStorage.get<number>('mic') as number + 1;
129        AppStorage.set('mic', mic);
130        console.log(TAG + 'onCreate : ' + 'AppStorage.get<number>(mic) : ' + AppStorage.get<number>('mic'));
131      }
132
133      if (want.parameters['returnCode'] == 24200102) {
134        try {
135          this.context.terminateSelf((err: BusinessError) => {
136            if (err.code) {
137              console.error(`terminateSelf failed,code is ${err.code},message is ${err.message}`);
138              return;
139            }
140            console.log(TAG + 'terminateSelf succeed');
141          });
142        } catch (err) {
143          let code = (err as BusinessError).code;
144          let message = (err as BusinessError).message;
145          console.error(`terminateSelf failed,code is ${code},message is ${message}`);
146        }
147      }
148    }
149  }
150
151  onNewWant(want: Want) {
152    console.info(TAG + 'onNewWant : ' + 'Ability onNewWant');
153
154    if (want.parameters != undefined) {
155      console.info(TAG + 'onNewWant : want.parameters : ' + JSON.stringify(want.parameters));
156      console.info(TAG + "onNewWant : want.parameters['returnCode'] : " + JSON.stringify(want.parameters['returnCode']));
157      console.info(TAG + "onNewWant : want.parameters['type'] : " + JSON.stringify(want.parameters['type']));
158
159      AppStorage.setOrCreate('returnCode', want.parameters['returnCode']);
160      AppStorage.setOrCreate('type', want.parameters['type']);
161
162      let returnCode: number = want.parameters['returnCode'] as number;
163      console.info(TAG + 'onNewWant : returnCode : ' + returnCode);
164      AppStorage.setOrCreate('returnCode', returnCode);
165
166      // returnCode==undefined:type+1
167      if (returnCode == undefined) {
168        // 切换前后置后刷新按钮文本为‘暂停’
169        AppStorage.setOrCreate('isPause', true);
170        console.log(TAG + 'onNewWant : refresh Btn Text : ' + 'AppStorage.get<boolean>(isPause) : ' + AppStorage.get<boolean>('isPause'));
171
172        if (want.parameters['type'] == 1) {
173          let camera: number = AppStorage.get<number>('camera') as number + 1;
174          AppStorage.set('camera', camera);
175          AppStorage.setOrCreate('switchedCamera', camera);
176          console.log(TAG + 'onNewWant : ' + '[returnCode==undefined]--[stop camera]--AppStorage.get<number>(camera) : ' + AppStorage.get<number>('camera'));
177        } else if (want.parameters['type'] == 1024) {
178          let mic: number = AppStorage.get<number>('mic') as number + 1;
179          AppStorage.set('mic', mic);
180          console.log(TAG + 'onNewWant : ' + '[returnCode==undefined]--[stop mic]--AppStorage.get<number>(mic) : ' + AppStorage.get<number>('mic'));
181        }
182      }
183
184      // returnCode == 24200102: stopAbility called
185      if (returnCode == 24200102) {
186        this.isStopAbility = true;
187        console.info(TAG + 'onNewWant :[returnCode == 24200102] this.isStopAbility : ' + this.isStopAbility);
188
189        // stopAbility:type-1
190        if (want.parameters['type'] == 1) {
191          let camera: number = AppStorage.get<number>('camera') as number - 1;
192          AppStorage.set('camera', camera);
193          console.log(TAG + 'onNewWant : ' + '[returnCode==24200102]--[stop camera]--AppStorage.get<number>(camera) : ' + AppStorage.get<number>('camera'));
194        } else if (want.parameters['type'] == 1024) {
195          let mic: number = AppStorage.get<number>('mic') as number - 1;
196          AppStorage.set('mic', mic);
197          console.log(TAG + 'onNewWant : ' + '[returnCode==24200102]--[stop mic]--AppStorage.get<number>(mic) : ' + AppStorage.get<number>('mic'));
198        }
199
200        if (AppStorage.get<number>('camera') == 0 && AppStorage.get<number>('mic') == 0) {
201          try {
202            this.context.terminateSelf((err: BusinessError) => {
203              if (err.code) {
204                console.error(`terminateSelf failed, code is ${err.code}, message is ${err.message}`);
205                return;
206              }
207              console.info(TAG + 'terminateSelf succeed');
208            });
209          } catch (err) {
210            let code = (err as BusinessError).code;
211            let message = (err as BusinessError).message;
212            console.error(`terminateSelf failed, code is ${code}, message is ${message}`);
213          }
214        }
215      }
216    }
217  }
218
219  onDestroy() {
220    console.info(TAG + 'onDestroy : ' + 'Ability onDestroy');
221
222    let sign: string = AppStorage.get<string>('sign') as string;
223    if (sign == 'stop') {
224      return;
225    }
226    let stopFlag = AppStorage.get<number>('camera') == 0 && AppStorage.get<number>('mic') == 0;
227
228    // stopAbility:app destroys itself: the stop function is no longer executed
229    if (!stopFlag && AppStorage.get<string>('sign') != 'onBackPress') {
230      console.info(TAG + 'onDestroy : ' + 'this.isStopAbility : ' + this.isStopAbility);
231      console.info(TAG + 'onDestroy : ' + "AppStorage.get<string>('sign') : " + AppStorage.get<string>('sign'));
232      this.stop();
233      console.info(TAG + 'onDestroy : ' + 'Distributed Hardware stopped');
234    }
235
236  }
237
238  onWindowStageCreate(windowStage: window.WindowStage) {
239    // Main window is created, set main page for this ability
240    console.info(TAG + 'onWindowStageCreate : ' + 'Ability onWindowStageCreate');
241
242    windowStage.loadContent('pages/DHardwareUI', (err, data) => {
243      if (err.code) {
244        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
245        return;
246      }
247      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
248    });
249  }
250
251  onWindowStageDestroy() {
252    // Main window is destroyed, release UI related resources
253    console.info(TAG + 'onWindowStageDestroy : ' + 'Ability onWindowStageDestroy');
254
255  }
256
257  eventFunc() {
258    console.info(TAG + 'call anonymous eventFunc : pause');
259  }
260
261  onForeground() {
262    // Ability has brought to foreground
263    console.info(TAG + 'onForeground : ' + 'Ability onForeground');
264
265    // isInit:Whether the app is initialized for the first time into the background
266    AppStorage.setOrCreate('isInit', this.isInit);
267    console.info(TAG + 'onForeground : ' + " AppStorage.get<boolean>('isInit') : " + AppStorage.get<boolean>('isInit'));
268    console.info(TAG + 'onForeground : ' + " AppStorage.get<boolean>('isPauseTag') : " + AppStorage.get<boolean>('isPauseTag'));
269
270    // Back to foreground again: Neither initializing the page for the first time nor pausing state triggers the resume
271    if (!this.isInit && !AppStorage.get<boolean>('isPauseTag')) {
272      console.info(TAG + 'onForeground : ' + 'this.isInit : ' + this.isInit);
273
274      if (AppStorage.get<number>('camera') != 0 || AppStorage.get<number>('mic') != 0) {
275        console.log(TAG + 'onForeground : ' + 'AppStorage.get<number>(camera) : ' + AppStorage.get<number>('camera'));
276        console.log(TAG + 'onForeground : ' + 'AppStorage.get<number>(mic) : ' + AppStorage.get<number>('mic'));
277
278        this.resume();
279      }
280    }
281    this.isInit = false;
282    AppStorage.setOrCreate('isInit', false);
283    // Restore unClicked pause state: Click Pause state initialization
284    AppStorage.setAndLink('isPause', true);
285    console.info(TAG + 'onForeground : ' + "AppStorage.get<boolean>('isPause') : " + AppStorage.get<boolean>('isPause'));
286  }
287
288  onBackground() {
289    // Ability has back to background
290    console.info(TAG + 'onBackground : ' + 'Ability onBackground');
291
292    let sign: string = AppStorage.get<string>('sign') as string;
293    if (sign == 'stop') {
294      return;
295    }
296    // stopAbility:app destroys itself: the pause function is no longer executed
297    let stopFlag = AppStorage.get<number>('camera') == 0 && AppStorage.get<number>('mic') == 0;
298    console.log(TAG + 'onBackground : stopFlag : ' + stopFlag)
299    let isScreenLock = screenLock.isLocked();
300    console.log(TAG + 'onBackground : isScreenLock : ' + isScreenLock)
301    if (!stopFlag && !isScreenLock) {
302      console.info(TAG + 'onBackground : ' + 'this.isStopAbility : ' + this.isStopAbility);
303      this.pause();
304      console.info(TAG + 'onBackground : ' + 'Distributed Hardware paused');
305    }
306  }
307
308  onBackPressed() {
309    return true;
310  }
311}
312