HarmonyOS开发实例:【事件的订阅和发布】

介绍

本示例主要展示了公共事件相关的功能,实现了一个检测用户部分行为的应用。具体而言实现了如下几点功能:

1.通过订阅系统公共事件,实现对用户操作行为(亮灭屏、锁屏和解锁屏幕、断联网)的监测;

2.通过在用户主动停止监测行为时发布自定义有序公共事件,实现对用户主动触发监听行为的持久化记录;

3.通过在用户设置对某一事件的监听状态时发布粘性事件,记录下本次应用运行期间允许监听的事件列表,同时在应用退出时将临时允许的修改为不允许;

4.打开自定义订阅事件页面需先安装[CardEvent]应用,通过订阅指定应用事件,实现用户对指定卡片发送事件的监听。

效果预览

订阅系统公共事件,主动停止监听行为及对某一事件的监听状态时发布粘性事件

image.png

使用说明:鸿蒙开发文档参考了gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md点击或者复制转到即可。

1.安装编译生成的hap包,依赖包hap,桌面上显示应用图标如下,点击图标即可进入应用。

image.png

2.进入应用显示菜单页,可选择“进入”,“历史”,“设置”及“关于”几个选项。

3.点击“进入”后跳转至主页面,点击主页面“开始监控”按钮,将开始监听系统公共事件,并进行计时,此时按钮内容变更为“停止监听”;点击停止监听按钮,页面上将显示本次监听时长及监听期间收到的干扰信息汇总,并在页面右下角显示“查看详情”按钮,点击按钮将跳转至详情页,显示监听期间收到的干扰信息,应用当前仅监听了亮灭屏、锁屏和解锁屏幕、断联网等用户可操作的系统公共事件,后续可根据需求快速扩展。

4.返回至应用菜单页面,点击“历史”可查看用户操作监听的历史记录,当前支持每次运行期间最多存储10条历史记录,超过10条后将删除历史数据。

5.返回至应用菜单页面,点击“设置”可进行具体系统事件的监听配置,应用提供了“一直”、“仅本次”及“从不”三个选项,其中“仅本次”选项是指本次应用运行期间将监听特定系统公共事件,应用退出后该选项将自动调整为“从不”。

6.在设置页面,点击“自定义事件定向订阅”进入订阅页面,

  • 点击”订阅“按钮进行订阅事件,同时订阅指定本应用事件和订阅非指定应用事件。
  • 点击应用内卡片发送事件或点击应用外卡片发送事件。
  • 点击应用内卡片发送事件后,指定应用事件和非指定应用事件均会接收到卡片所发送的事件 ;点击应用外卡片发送事件后,非指定应用事件会被接收,指定应用事件不会被接收。
  • 点击”取消订阅“ 页面中会提示当前事件取消订阅。

7.返回至应用菜单页面,点击“关于”可查看应用版本信息及本示例的说明。

搜狗高速浏览器截图20240326151547.png

代码解读

CustomCommonEvent

HarmonyOS与OpenHarmony开发文档+mau123789是v直接拿取
entry/src/main/ets/
|---Application
|   |---MyAbilityStage.ts                    
|---component
|   |---Header.ets                           // 头部组件
|---entryformability
|   |---EntryFormAbility.ts                  // 卡片提供方  
|---feature
|   |---HistoryFeature.ts                    
|   |---LaunchFeature.ts                    
|   |---MainFeature.ts                    
|   |---SettingFeature.ts                    
|---LauncherAbility 
|   |---LauncherAbility.ts
|---MainAbility
|   |---MainAbility.ts
|---model
|   |---Consts.ts                            // 数据定义
|   |---Logger.ts                            // 日志打印  
|   |---SurveillanceEventsManager.ts         // 公共事件模块
|   |---Utils.ts                        
|---pages
|   |---About.ets                            // 关于页面
|   |---Detail.ets                           // 详情页面
|   |---History.ets                          // 历史页面
|   |---jumpToCommonEvent.ets                // 自定义订阅事件页面
|   |---Launch.ets                           // 发起页面
|   |---Main.ets                             // 进入页面
|   |---Setting.ets                          // 设置页面
|---publishcard
|   |---pages
|   |	|---PublishCard.ets              	 // 卡片页面

CustomCommonEventRely

entry/src/main/ets/
|---entryformability
|   |---EntryFormAbility.ts					// 发布事件
|---pages
|   |---Index.ets
|---widget
|   |---pages
|   |	|---PublishCard.ets 				// 发布事件的卡片

具体实现

  • 该示例entry部分分为五个模块:

    • 进入模块

      • 使用到应用文上下文,createSubscriber方法创建订阅者,getCurrentTime获取获取自Unix纪元以来经过的时间进行对用户操作行为的监测功能页面开发。
  • 源码链接:[Consts.ts]

/** Copyright (c) 2022-2023 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import commonEvent from '@ohos.commonEventManager';export default class consts {// definition for databasestatic readonly DATA_BASE_NAME: string = "nothing_pre";static readonly DATA_BASE_KEY_TOTAL_TIMES: string = "totalTimes";static readonly DATA_BASE_KEY_START_TIME: string = "startTime";static readonly DATA_BASE_KEY_WIFI_POWER_STATE: string = commonEvent.Support.COMMON_EVENT_WIFI_POWER_STATE;static readonly DATA_BASE_KEY_SCREEN_OFF: string = commonEvent.Support.COMMON_EVENT_SCREEN_OFF;static readonly DATA_BASE_KEY_SCREEN_ON: string = commonEvent.Support.COMMON_EVENT_SCREEN_ON;static readonly DATA_BASE_KEY_SCREEN_LOCKED: string = commonEvent.Support.COMMON_EVENT_SCREEN_LOCKED;static readonly DATA_BASE_KEY_SCREEN_UNLOCKED: string = commonEvent.Support.COMMON_EVENT_SCREEN_UNLOCKED;static readonly DATA_BASE_KEY_ONCE_EVENTS: string = "onceCall";static readonly DATA_BASE_KEY_NEVER_EVENTS: string = "neverCall";// definition for event enable statestatic readonly ENABLE_STATE_ALWAYS : number = 0static readonly ENABLE_STATE_ONCE : number = 1static readonly ENABLE_STATE_NEVER : number = 2// definition for record volumestatic readonly MAX_RECORD_NUM: number = 10;// definition for self defined common eventsstatic readonly COMMON_EVENT_FINISH_MEDITATION: string = "finish_meditation"static readonly COMMON_EVENT_SETTING_UPDATE: string = "setting_update"}

[LaunchFeature.ts]

/** Copyright (c) 2024 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import common from '@ohos.app.ability.common';import commonEvent from '@ohos.commonEventManager';import dataPreferences from '@ohos.data.preferences';import Want from '@ohos.app.ability.Want';import router from '@ohos.router';import consts from '../module/Consts';import Logger from '../module/Logger';export default class LaunchFeature {private innerContext: common.UIAbilityContext = null;private pref: dataPreferences.Preferences = null;private subscriber = null;private subscriberLow = null;private currentRecordTimes: number = 0;constructor(abilityContext: common.UIAbilityContext) {this.innerContext = abilityContext;}async init(): Promise<void> {await dataPreferences.getPreferences(this.innerContext, consts.DATA_BASE_NAME).then((pref) => {this.pref = pref;});await this.pref.get(consts.DATA_BASE_KEY_WIFI_POWER_STATE, 0).then((value: number) => {globalThis.settings.set(commonEvent.Support.COMMON_EVENT_WIFI_POWER_STATE, value);});await this.pref.get(consts.DATA_BASE_KEY_SCREEN_OFF, 0).then((value1: number) => {globalThis.settings.set(commonEvent.Support.COMMON_EVENT_SCREEN_OFF, value1);});await this.pref.get(consts.DATA_BASE_KEY_SCREEN_ON, 0).then((value2: number) => {globalThis.settings.set(commonEvent.Support.COMMON_EVENT_SCREEN_ON, value2);});await this.pref.get(consts.DATA_BASE_KEY_SCREEN_LOCKED, 0).then((value3: number) => {globalThis.settings.set(commonEvent.Support.COMMON_EVENT_SCREEN_LOCKED, value3);});await this.pref.get(consts.DATA_BASE_KEY_SCREEN_UNLOCKED, 0).then((value4: number) => {globalThis.settings.set(commonEvent.Support.COMMON_EVENT_SCREEN_UNLOCKED, value4);});}private insertRecord = (event, value) => {value.push(event.parameters[consts.DATA_BASE_KEY_START_TIME]);// refresh databasethis.pref.put(consts.DATA_BASE_KEY_TOTAL_TIMES, value).then(() => {let detail: Array<string> = [];detail.push(event.parameters["startTime"]);detail.push(event.parameters["endTime"]);detail.push(event.parameters["totalTime"]);detail.push(event.parameters["totalEvents"]);this.pref.put(event.parameters[consts.DATA_BASE_KEY_START_TIME], detail).then(() => {this.pref.flush()})});}private callbackFunc = (error, event) => {this.pref.has(consts.DATA_BASE_KEY_TOTAL_TIMES, (err, ret) => {if (ret) {this.pref.get(consts.DATA_BASE_KEY_TOTAL_TIMES, []).then((value) => {this.insertRecord(event, value);});} else {let value: Array<string> = [];this.insertRecord(event, value);}if (this.currentRecordTimes >= consts.MAX_RECORD_NUM) {this.subscriber.finishCommonEvent();return;}this.subscriber.abortCommonEvent();this.subscriber.finishCommonEvent();this.currentRecordTimes++;})}private callbackLowFunc = (error, event) => {this.currentRecordTimes = 1;this.pref.get(consts.DATA_BASE_KEY_TOTAL_TIMES, []).then((value: Array<string>) => {for (let i = 0; i < consts.MAX_RECORD_NUM; i++) {this.pref.delete(value[i]).then(() => {this.pref.flush();this.subscriberLow.finishCommonEvent();})}let records = value.slice(consts.MAX_RECORD_NUM, consts.MAX_RECORD_NUM + 1);this.pref.put(consts.DATA_BASE_KEY_TOTAL_TIMES, records);this.pref.flush();})}jumpToStart = () => {// subscribeif (this.subscriber == null) {let highSubscriberInfo = {events: [consts.COMMON_EVENT_FINISH_MEDITATION // unordered self defined event],priority: 2 // 2 indicates high priority subscriber};commonEvent.createSubscriber(highSubscriberInfo, (err, subscriber) => {this.subscriber = subscriberif (subscriber != null) {commonEvent.subscribe(subscriber, this.callbackFunc)}});}// subscribeif (this.subscriberLow == null) {let lowSubscriberInfo = {events: [consts.COMMON_EVENT_FINISH_MEDITATION // unordered self defined event],priority: 1 // 1 indicates low priority subscriber};commonEvent.createSubscriber(lowSubscriberInfo, (updaerr, subscriber) => {this.subscriberLow = subscriberif (subscriber != null) {commonEvent.subscribe(subscriber, this.callbackLowFunc)}});}let want = {bundleName: 'com.samples.customcommonevent',abilityName: 'MainAbility',};this.innerContext.startAbility(want);}jumpToHistory = () => {Logger.info("ready to jump to history page");router.pushUrl({url: 'pages/History',params: {}});}jumpToSetting = () => {Logger.info("ready to jump to setting page");router.pushUrl({url: 'pages/Setting',params: {}});}jumpToAbout = () => {Logger.info("ready to jump to about page");router.pushUrl({url: 'pages/About',params: {}});}jumpToCommonEvent = (): void => {Logger.info('ready to jump to commonEvent page');let context: common.UIAbilityContext | undefined = AppStorage.get('context');let want: Want = {bundleName: "com.samples.cardevent",abilityName: "EntryAbility",};context && context.startAbility(want,  (err) => {if (err.code) {Logger.error('StartAbility', `Failed to startAbility. Code: ${err.code}, message: ${err.message}`);}});};}

[LauncherAbility.ts]

/** Copyright (c) 2022-2023 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import UIAbility from '@ohos.app.ability.UIAbility';import commonEvent from '@ohos.commonEventManager';import consts from '../module/Consts';import dataPreferences from '@ohos.data.preferences';import surveillanceEventsManager from '../module/SurveillanceEventsManager';import Logger from '../module/Logger';export default class LauncherAbility extends UIAbility {onCreate(want) {globalThis.abilityWant = want;let settings: Map<string, number> = new Map();surveillanceEventsManager.surveillanceEvents.forEach((element: string) => {settings.set(element, consts.ENABLE_STATE_ALWAYS);});globalThis.settings = settings;AppStorage.setOrCreate('context', this.context);Logger.info(`LauncherAbility onCreate, settings.size = ${globalThis.settings.size}`)}async onDestroy() {Logger.info("LauncherAbility onDestroy")globalThis.settings.forEach((value: number, key: string) => {if (value == consts.ENABLE_STATE_ONCE) {globalThis.settings.set(key, consts.ENABLE_STATE_NEVER);}});let thisPref = null;await dataPreferences.getPreferences(this.context, consts.DATA_BASE_NAME).then((pref) => {thisPref = pref;});for (let element of surveillanceEventsManager.surveillanceEvents) {await thisPref.put(element, globalThis.settings.get(element));};await thisPref.flush();let options = {isSticky: true,parameters: surveillanceEventsManager.getSurveillanceEventStates()};commonEvent.publish(consts.COMMON_EVENT_SETTING_UPDATE, options, () => {Logger.info("success to publish once enable event");});}onWindowStageCreate(windowStage) {// Main window is created, set main page for this abilitywindowStage.loadContent("pages/Launch", (err, data) => {if (err.code) {Logger.error('Failed to load the content. Cause:' + JSON.stringify(err));return;}Logger.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));});}onWindowStageDestroy() {// Main window is destroyed, release UI related resourcesLogger.info("LauncherAbility onWindowStageDestroy");}onForeground() {// Ability has brought to foregroundLogger.info("LauncherAbility onForeground");}onBackground() {// Ability has back to backgroundLogger.info("LauncherAbility onBackground");}}

[SurveillanceEventsManager.ts]

/** Copyright (c) 2022-2023 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import commonEvent from '@ohos.commonEventManager';export class EventData {"usual.event.wifi.POWER_STATE": number;"usual.event.SCREEN_OFF": number;"usual.event.SCREEN_ON": number;"usual.event.SCREEN_LOCKED": number;"usual.event.SCREEN_UNLOCKED": number;}export default class SurveillanceEventsManager {constructor() {}static getSurveillanceEventStates(): EventData {return {"usual.event.wifi.POWER_STATE": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_WIFI_POWER_STATE),"usual.event.SCREEN_OFF": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_SCREEN_OFF),"usual.event.SCREEN_ON": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_SCREEN_ON),"usual.event.SCREEN_LOCKED": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_SCREEN_LOCKED),"usual.event.SCREEN_UNLOCKED": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_SCREEN_UNLOCKED)}}static surveillanceEvents: Array<string> = [commonEvent.Support.COMMON_EVENT_WIFI_POWER_STATE,commonEvent.Support.COMMON_EVENT_SCREEN_OFF,commonEvent.Support.COMMON_EVENT_SCREEN_ON,commonEvent.Support.COMMON_EVENT_SCREEN_LOCKED,commonEvent.Support.COMMON_EVENT_SCREEN_UNLOCKED,]}
  • 参考接口:[@ohos.app.ability.common],[@ohos.commonEventManager],[@ohos.data.preferences],[@ohos.commonEvent],[@ohos.router],[@ohos.systemTime]

    • 历史模块

      • 使用到应用文上下文,getPreferences方法获取Preferences实例,组件Header进行历史页面开发。
  • 源码链接:[Header.ets]

/** Copyright (c) 2022 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import router from '@ohos.router'@Componentexport struct Header {@State src: string = ''build() {Column() {}.backgroundImage($rawfile(this.src)).backgroundImageSize(ImageSize.Cover).position({ x: '2%', y: '2%' }).size({ width: 100, height: 50 }).onClick(() => {router.back()})}}

[Consts.ts]

/** Copyright (c) 2022-2023 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import commonEvent from '@ohos.commonEventManager';export default class consts {// definition for databasestatic readonly DATA_BASE_NAME: string = "nothing_pre";static readonly DATA_BASE_KEY_TOTAL_TIMES: string = "totalTimes";static readonly DATA_BASE_KEY_START_TIME: string = "startTime";static readonly DATA_BASE_KEY_WIFI_POWER_STATE: string = commonEvent.Support.COMMON_EVENT_WIFI_POWER_STATE;static readonly DATA_BASE_KEY_SCREEN_OFF: string = commonEvent.Support.COMMON_EVENT_SCREEN_OFF;static readonly DATA_BASE_KEY_SCREEN_ON: string = commonEvent.Support.COMMON_EVENT_SCREEN_ON;static readonly DATA_BASE_KEY_SCREEN_LOCKED: string = commonEvent.Support.COMMON_EVENT_SCREEN_LOCKED;static readonly DATA_BASE_KEY_SCREEN_UNLOCKED: string = commonEvent.Support.COMMON_EVENT_SCREEN_UNLOCKED;static readonly DATA_BASE_KEY_ONCE_EVENTS: string = "onceCall";static readonly DATA_BASE_KEY_NEVER_EVENTS: string = "neverCall";// definition for event enable statestatic readonly ENABLE_STATE_ALWAYS : number = 0static readonly ENABLE_STATE_ONCE : number = 1static readonly ENABLE_STATE_NEVER : number = 2// definition for record volumestatic readonly MAX_RECORD_NUM: number = 10;// definition for self defined common eventsstatic readonly COMMON_EVENT_FINISH_MEDITATION: string = "finish_meditation"static readonly COMMON_EVENT_SETTING_UPDATE: string = "setting_update"}

[HistoryFeature.ts]

/** Copyright (c) 2022-2023 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import common from '@ohos.app.ability.common'import consts from '../module/Consts'import dataPreferences from '@ohos.data.preferences'import Logger from '../module/Logger'const TAG: string = '[Sample_CustomCommonEvent_HistoryFeature]'export default class HistoryFeature {constructor(abilityContext: common.UIAbilityContext) {this.innerContext = abilityContext}async getData() {await this.init()return new Promise((resolve) => {resolve(this.dataSource)})}private async init() {let prefer = nullawait dataPreferences.getPreferences(this.innerContext, consts.DATA_BASE_NAME).then((pref) => {prefer = pref})let records: Array<string>await prefer.get(consts.DATA_BASE_KEY_TOTAL_TIMES, []).then((value: Array<string>) => {records = value})for (let item of records) {await prefer.get(item, []).then((detail: Array<string>) => {if(JSON.stringify(detail) !== '[]'){this.dataSource.push(detail)}}).catch((error)=>{Logger.info(TAG, `Failed to get value code is ${error.code}`)})}}private dataSource: Array<Array<string>> = []private innerContext: common.UIAbilityContext = null}
  • 参考接口:[@ohos.app.ability.common],[@ohos.data.preferences]

    • 设置模块

      • 本模块分为三个事件,分别为记录联网事件,记录灭屏事件,记录亮屏事件,进行锁屏事件、进行解锁屏幕事件,每一个事件都可进行一直,仅本次和从不的单项选择,使用到应用文上下文吗,CommonEvent.publish发布公共事件,getPreferences方法获取Preferences实例进行功能页面开发。
      • 源码链接:[Header.ets],[Consts.ts]

[SettingFeature.ts]

/** Copyright (c) 2022 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import commonEvent from '@ohos.commonEventManager';import common from '@ohos.app.ability.common';import consts from '../module/Consts';import dataPreferences from '@ohos.data.preferences';import Logger from '../module/Logger';import surveillanceEventsManager from '../module/SurveillanceEventsManager';export default class SettingFeature {private innerContext: common.UIAbilityContext = nullprivate pref: dataPreferences.Preferences = nullconstructor(abilityContext: common.UIAbilityContext) {this.innerContext = abilityContext}async init() {await dataPreferences.getPreferences(this.innerContext, consts.DATA_BASE_NAME).then((pref=>{this.pref = pref})).catch(err=>{Logger.info(`getPreferences err ${JSON.stringify(err)}`)})}changeState(group: string, state: number) {globalThis.settings.set(group, state);let options = {isSticky: true,parameters: surveillanceEventsManager.getSurveillanceEventStates()}commonEvent.publish(consts.COMMON_EVENT_SETTING_UPDATE, options, () => {Logger.info('success to publish setting update event')})this.pref.put(group, state).then(() => {this.pref.flush()})}checkStateForAlways(group: string): boolean {return globalThis.settings.get(group) == consts.ENABLE_STATE_ALWAYS}checkStateForOnce(group: string): boolean {return globalThis.settings.get(group) == consts.ENABLE_STATE_ONCE}checkStateForNever(group: string): boolean {return globalThis.settings.get(group) == consts.ENABLE_STATE_NEVER}changeStateToAlways(group: string) {this.changeState(group, consts.ENABLE_STATE_ALWAYS)}changeStateToOnce(group: string) {this.changeState(group, consts.ENABLE_STATE_ONCE)}changeStateToNever(group: string) {this.changeState(group, consts.ENABLE_STATE_NEVER)}}

[SurveillanceEventsManager.ts]

/** Copyright (c) 2022-2023 Huawei Device Co., Ltd.* Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import commonEvent from '@ohos.commonEventManager';export class EventData {"usual.event.wifi.POWER_STATE": number;"usual.event.SCREEN_OFF": number;"usual.event.SCREEN_ON": number;"usual.event.SCREEN_LOCKED": number;"usual.event.SCREEN_UNLOCKED": number;}export default class SurveillanceEventsManager {constructor() {}static getSurveillanceEventStates(): EventData {return {"usual.event.wifi.POWER_STATE": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_WIFI_POWER_STATE),"usual.event.SCREEN_OFF": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_SCREEN_OFF),"usual.event.SCREEN_ON": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_SCREEN_ON),"usual.event.SCREEN_LOCKED": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_SCREEN_LOCKED),"usual.event.SCREEN_UNLOCKED": globalThis.settings.get(commonEvent.Support.COMMON_EVENT_SCREEN_UNLOCKED)}}static surveillanceEvents: Array<string> = [commonEvent.Support.COMMON_EVENT_WIFI_POWER_STATE,commonEvent.Support.COMMON_EVENT_SCREEN_OFF,commonEvent.Support.COMMON_EVENT_SCREEN_ON,commonEvent.Support.COMMON_EVENT_SCREEN_LOCKED,commonEvent.Support.COMMON_EVENT_SCREEN_UNLOCKED,]}
  • 参考接口:[@ohos.app.ability.common],[@ohos.data.preferences],[@ohos.commonEvent],[@ohos.router],[@ohos.commonEvent]

    • 关于模块

      • 该模块开发主要介绍了本示例的功能作用以及说明了什么情况下不能使用。
      • 源码链接:[Header.ets],[Consts.ts]
    • 设置中订阅事件模块

      • 本模块主要支持指定应用订阅自定义事件。subScribeInfo新增可选属性publisherBundleName,创建订阅对象时可指定PublisherBundlerName,事件发布时,获取订阅者信息,增加校验bundleName是否等于publisherBundlerName,相等则加入事件回调方,达成只接收指定发布方发布的事件的效果。
      • 源码链接:[EntryFormAbility.ts],[PublishCard.ets]
      • 参考接口:[@ohos.commonEventManager],[@ohos.hilog],[@ohos.app.form.formInfo],[@ohos.app.form.formBindingData],[@ohos.app.form.FormExtensionAbility]

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/818582.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

vmware安装ubuntu-18.04系统

一、软件下载 百度网盘&#xff1a; 链接&#xff1a;https://pan.baidu.com/s/1fK2kygRdSux1Sr1sOKOtJQ 提取码&#xff1a;twsb 二、安装ubuntu系统 1、把ubuntu-18.04的压缩包下载下来&#xff0c;并且解压 2、打开vmware软件&#xff0c;点击文件-打开 3、选择我们刚刚解…

6. Django 深入模板

6. 深入模板 6.1 Django模板引擎 Django内置的模板引擎包含模板上下文(亦可称为模板变量), 标签和过滤器, 各个功能说明如下: ● 模板上下文是以变量的形式写入模板文件里面, 变量值由视图函数或视图类传递所得. ● 标签是对模板上下文进行控制输出, 比如模板上下文的判断和循…

项目7-音乐播放器1+BCrypt加密

1.创建项目 1.1 引入依赖 1.2 yml相关配置 application.yml spring:profiles:active: prod mybatis:mapper-locations: classpath:mapper/**Mapper.xmlconfiguration:map-underscore-to-camel-case: true #配置驼峰⾃动转换log-impl: org.apache.ibatis.logging.stdout.StdO…

openGauss学习笔记-261 openGauss性能调优-使用Plan Hint进行调优-将部分Error降级为Warning的Hint

文章目录 openGauss学习笔记-261 openGauss性能调优-使用Plan Hint进行调优-将部分Error降级为Warning的Hint261.1 功能描述261.2 语法格式261.3 示例261.3.1 忽略非空约束261.3.2 忽略唯一约束261.3.3 忽略分区表无法匹配到合法分区261.3.4 更新/插入值向目标列类型转换失败 o…

【算法】数组元素循环右移k位,并要求只用一个元素大小的附加存储,元素移动或交换次数为O(n)

两种写法思路&#xff1a; 思路一&#xff1a;三次倒置 前言&#xff1a;C/C函数 reverse 是 左闭右开区间的&#xff0c;作用是将指定范围数组元素全部倒置&#xff0c;数组从 0 开始&#xff0c;这里主要讲解思路&#xff0c;就直接用 函数 reverse 简化过程 这个方法 实现 …

vue3第十八节(diff算法)

引言&#xff1a; 上一节说了key的用途&#xff0c;而这个key属性&#xff0c;在vue的vnode 中至关重要&#xff0c;直接影响了虚拟DOM的更新机制&#xff1b; 什么场景中会用到diff算法 如&#xff1a;修改响应式属性需要重新渲染页面&#xff0c;会重新执行render渲染函数返…

为了执行SQL语句,MySQL的架构是怎样设计的

1. 把MySQL当个黑盒子一样执行SQL语句 上一讲我们已经说到&#xff0c;我们的系统采用数据库连接池的方式去并发访问数据库&#xff0c;然后数据库自己其实也会维护一个连 接池&#xff0c;其中管理了各种系统跟这台数据库服务器建立的所有连接 我们先看下图回顾一下 当我们的…

数据可视化-ECharts Html项目实战(12)

在之前的文章中&#xff0c;我们深入学习ECharts特殊图表中的矩形树图以及Echarts中高级功能的多图表联动。想了解的朋友可以查看这篇文章。同时&#xff0c;希望我的文章能帮助到你&#xff0c;如果觉得我的文章写的不错&#xff0c;请留下你宝贵的点赞&#xff0c;谢谢。 数…

Directory Monitor:全方位监控文件系统变动的专业利器

目录 一、软件介绍 二、软件功能 三、软件特点 四、安装说明 五、使用说明 一、软件介绍 Directory Monitor是一款强大易用的实时文件系统监视工具&#xff0c;它由Michael Humpa开发&#xff0c;专为满足用户监控特定目录下文件和子目录变化的需求。无论是为了保障系统安…

python与设计模式之工厂模式的那些事儿

一、工厂模式 工厂模式实现了按需创建的最佳模式&#xff0c;其目的是为了隐藏创建类的细节与过程&#xff0c;通过一个统一的接口来创建所需的对象。 话说没了皇位争夺权的皇三接到了一个外征的工作&#xff0c;始皇给了5个亿的经费让皇三组建一个军队。打权总是要进行武器采…

【Java开发指南 | 第二篇】标识符、Java关键字及注释

读者可订阅专栏&#xff1a;Java开发指南 |【CSDN秋说】 文章目录 标识符Java关键字Java注释 标识符 Java 所有的组成部分都需要名字。类名、变量名以及方法名都被称为标识符。 所有的标识符都应该以字母&#xff08;A-Z 或者 a-z&#xff09;,美元符&#xff08;$&#xff0…

CentOS 7安装、卸载MySQL数据库

说明&#xff1a;本文介绍如何在CentOS 7操作系统下使用yum方式安装MySQL数据库&#xff0c;及卸载&#xff1b; 安装 Step1&#xff1a;卸载mariadb 敲下面的命令&#xff0c;查看系统mariadb软件包 rpm -qa|grep mariadb跳出mariadb软件包信息后&#xff0c;敲下面的命令…

【Qt】:事件的处理

系统相关 一.鼠标事件二.键盘事件三.定时器 事件是应用程序内部或者外部产生的事情或者动作的统称。在Qt中使用一个对象来表示一个事件。所有的Qt事件均继承于抽象类QEvent。事件是由系统或者Qt平台本身在个同的的刻友出的。当用广投下鼠标、敲下键盘&#xff0c;或者是窗口需要…

第四百六十二回

文章目录 1. 概念介绍2. 实现方法3. 示例代码4. 内容总结 我们在上一章回中介绍了"关于MediaQuery的优化"相关的内容&#xff0c;本章回中将介绍readMore这个三方包.闲话休提&#xff0c;让我们一起Talk Flutter吧。 1. 概念介绍 我们在本章回中介绍的readMore是一个…

【团体程序设计天梯赛 往年关键真题 25分题合集 详细分析完整AC代码】(L2-001 - L2-024)搞懂了赛场上拿下就稳了

L2-001 紧急救援 最短路路径打印 样例 输入1 4 5 0 3 20 30 40 10 0 1 1 1 3 2 0 3 3 0 2 2 2 3 2输出1 2 60 0 1 3分析 用一遍dijkstra算法。设立 n u m [ i ] num[i] num[i]和 w [ i ] w[i] w[i]表示从出发点到i结点拥有的路的条数&#xff0c;以及能够找到的救援队的数目…

Websocket (帧格式, 握手过程, Spring 中使用 WebScoket 协议)

什么是 WebSocket 客户端 A 和客户端 B 的消息传播需要借助服务器的中转 (原因是内网不能给另一个局域网的内网直接联通, 需要借助服务器的外网做 “中介”) (NAT 地址转换) Http 协议 不支持实时通讯 (或者说不支持服务器主动推送数据给客户端) TCP 本身是具有服务器推送数据这…

【verilog】 reg与寄存器的关系

一、前言 在Verilog中经常用reg定义具有数据寄存功能的单元&#xff0c;但在verilog的使用中&#xff0c;并不代表其一定就是寄存单元&#xff0c;reg还能进行组合逻辑描述&#xff0c;并且在一些场景下&#xff0c;只能使用reg来申明变量。 二、reg型变量生成组合逻辑 在Ve…

linux shell脚本编写(2)

Shell: 命令转换器&#xff0c;高级语言转换成二进制语言。是Linux的一个外壳&#xff0c;它包在Lniux内核的外面&#xff0c;用户和内核之间的交互提供了一个接口。 内置命令&#xff1a;在shell内部不需要shell编辑 外置命令&#xff1a;高级语言要用shell转换成二进制语言 …

(一)Jetpack Compose 从入门到会写

基本概念 Compose 名称由来 众所周知&#xff0c;继承在功能拓展上表现的很脆弱&#xff0c;容易类、函数爆炸&#xff0c;通过代理和包装进行组合会更健壮。 Compose 意为组合&#xff0c;使用上也是把 Compose 函数以 模拟函数调用层级关系的方式 组合到一起&#xff0c;最终…

PCL中VTK场景添加坐标系轴显示

引言 世上本没有坐标系&#xff0c;用的人多了&#xff0c;便定义了坐标系统用来定位。地理坐标系统用于定位地球上的位置&#xff0c;PCL点云库可视化窗口中的坐标系统用于定位其三维世界中的位置。本人刚开始接触学习PCL点云库&#xff0c;计算机图形学基础为零&#xff0c;…