1/* 2 * Copyright (c) 2025 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 */ 15import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 16import { hilog } from '@kit.PerformanceAnalysisKit'; 17import { window } from '@kit.ArkUI'; 18import { commonEventManager } from '@kit.BasicServicesKit'; 19 20const DOMAIN = 0x0000; 21 22export default class SingletonAbility extends UIAbility { 23 private exitTask: number = 0; 24 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 25 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate'); 26 commonEventManager.publish('demo2_singleton_onCreate', {}, () => {}); 27 } 28 29 onDestroy(): void { 30 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy'); 31 } 32 33 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void { 34 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onNewWant'); 35 commonEventManager.publish('demo2_singleton_onNewWant', {}, () => {}); 36 } 37 38 onWindowStageCreate(windowStage: window.WindowStage): void { 39 // Main window is created, set main page for this ability 40 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate'); 41 42 windowStage.loadContent('pages/Singleton', (err) => { 43 if (err.code) { 44 hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err)); 45 return; 46 } 47 hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.'); 48 }); 49 } 50 51 onWindowStageDestroy(): void { 52 // Main window is destroyed, release UI related resources 53 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy'); 54 } 55 56 onForeground(): void { 57 // Ability has brought to foreground 58 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground'); 59 if (this.exitTask !== 0) { 60 return; 61 } 62 this.exitTask = setTimeout(() => { 63 hilog.info(DOMAIN, 'testTag', '%{public}s', 'demo2 singleton terminateSelf'); 64 commonEventManager.publish('demo2_singleton_Exit', {}, () => { 65 this.context.terminateSelf(); 66 }); 67 }, 500); 68 } 69 70 onBackground(): void { 71 // Ability has back to background 72 hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground'); 73 } 74} 75