1/* 2 * Copyright (c) 2022 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 commonEvent from '@ohos.commonEvent'; 17import { CommonEventSubscriber } from 'commonEvent/commonEventSubscriber'; 18import createOrGet from './SingleInstanceHelper'; 19import EventManager from './event/EventManager'; 20import Log from './Log'; 21import { obtainLocalEvent } from './event/EventUtil'; 22import { debounce } from './Decorators'; 23 24export const SCREEN_CHANGE_EVENT = 'screenChangeEvent'; 25 26const TAG = 'ScreenLockManager'; 27const SCREEN_COMMON_EVENT_INFO = { 28 events: [commonEvent.Support.COMMON_EVENT_SCREEN_OFF, commonEvent.Support.COMMON_EVENT_SCREEN_ON], 29}; 30const debounceTimeout = 500; 31 32class ScreenLockManager { 33 mSubscriber: CommonEventSubscriber | undefined; 34 35 async init(): Promise<void> { 36 this.mSubscriber = await commonEvent.createSubscriber(SCREEN_COMMON_EVENT_INFO); 37 commonEvent.subscribe(this.mSubscriber, (err, data) => { 38 if (err.code != 0) { 39 Log.showError(TAG, `Can't handle screen change, err: ${JSON.stringify(err)}`); 40 return; 41 } 42 Log.showDebug(TAG, `screenChange, err: ${JSON.stringify(err)} data: ${JSON.stringify(data)}`); 43 switch (data.event) { 44 case commonEvent.Support.COMMON_EVENT_SCREEN_OFF: 45 this.notifyScreenEvent(false); 46 break; 47 case commonEvent.Support.COMMON_EVENT_SCREEN_ON: 48 this.notifyScreenEvent(true); 49 break; 50 default: 51 Log.showError(TAG, 'unknow event'); 52 } 53 }); 54 } 55 56 @debounce(debounceTimeout) 57 notifyScreenEvent(isScreenOn: boolean): void { 58 EventManager.publish(obtainLocalEvent(SCREEN_CHANGE_EVENT, isScreenOn)); 59 Log.showDebug(TAG, `publish ${SCREEN_CHANGE_EVENT} screenState: ${isScreenOn ? 'true' : 'false'}`); 60 } 61} 62 63let sScreenLockManager = createOrGet(ScreenLockManager, TAG); 64 65export default sScreenLockManager;