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.rhkb.cn/news/310624.html

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

相关文章

气象观测站点数据下载与处理

一、下载途径 全国400多个气象站气候数据&#xff08;1942-2022&#xff09; 王晓磊&#xff1a;中国空气质量/气象历史数据 | 北京市空气质量历史数据 气象数据免费下载网站整理 中国气象站观测的气象数据怎么下载 二、R语言处理 2.1 提取站点文件 library(dplyr) library(…

探索顶级短视频素材库:多样化选择助力创作

在数字创作的浪潮中&#xff0c;寻找优质的短视频素材库是每位视频制作者的必经之路。多种短视频素材库有哪些&#xff1f;这里为您介绍一系列精选的素材库&#xff0c;它们不仅丰富多样&#xff0c;而且高质量&#xff0c;能极大地提升您的视频创作效率和质量。 1.蛙学网 蛙学…

绝地求生:PWS韩国联赛结束:KDF夺冠,DNW三年来首次错失世界赛

4.14号PWS韩国联赛结束了为期3天的决赛&#xff0c;KDF战队以73击杀117分获PWS第一阶段冠军&#xff0c;队内Heaven获MVP&#xff0c;DK_seoul伤害王。 常规赛靠前的DNW和Gen.G决赛均发挥失常都没有进入前八&#xff0c;其中上届世界冠军DNW在双S核心出走后时隔三年首次错失世界…

ubuntu20.04安装+ros-noetic安装+内网穿透frp

刷机后的系统安装 ubuntu20.04安装安装ros-noetic安装各种必要的插件安装vscode内网穿透连接实验室主机配置frpc和frps文件运行完成自动化部署免密登录linux的免密登录windows上的免密登录 内网穿透的参考链接&#xff1a;如何优雅地访问远程主机&#xff1f;SSH与frp内网穿透配…

6、JVM-JVM调优工具与实战

前置启动程序 事先启动一个web应用程序&#xff0c;用jps查看其进程id&#xff0c;接着用各种jdk自带命令优化应用 Jmap 此命令可以用来查看内存信息&#xff0c;实例个数以及占用内存大小 jmap -histo 14660 #查看历史生成的实例 jmap -histo:live 14660 #查看当前存活的实…

SQL12 获取每个部门中当前员工薪水最高的相关信息

题目&#xff1a;获取每个部门中当前员工薪水最高的相关信息 注意了&#xff0c;这道题目&#xff0c;分组函数只能查出来&#xff1a;每个部门的最高薪水&#xff0c;group by dept_no &#xff0c;根据部门分组&#xff0c;绝对不能group by dept_no,emp_no&#xff0c;不能…

云正在使 IT 受益,但对业务却没有好处

云具有巨大的商业价值&#xff01;这是云提供商及其盟友在每次云计算会议上高喊的战斗口号。 您永远不会听到我说“云”始终是正确的解决方案&#xff0c;或者就此而言&#xff0c;是错误的解决方案。 在作为云专家 20 多年的时间里&#xff0c;从来没有盲目追随云计算先驱或…

Educational Codeforces Round 164 (Rated for Div. 2)

D. Colored Balls 题意&#xff1a;给你n个颜色不同的小球&#xff0c;以及每种颜色小球的数量&#xff0c;让你求 种集合分割方案的价值和 我们考虑一个集合的贡献&#xff0c;如果最大值大于sum的一半&#xff0c;那么值就是max&#xff0c;反之值就是(sum1)/2 那么我们可…

Docker Desktop修改镜像存储路径 Docker Desktop Start ... 卡死

1、CMD执行wsl -l -v --all 2、Clean / Purge data 3、导出wsl子系统镜像: wsl --export docker-desktop D:\docker\wsl\distro\docker-desktop.tar wsl --export docker-desktop-data D:\docker\wsl\data\docker-desktop-data.tar4、删除现有的wsl子系统&#xff1a; wsl -…

快速寻找可以构建出网通信隧道的计算机

点击星标&#xff0c;即时接收最新推文 本文选自《内网安全攻防&#xff1a;红队之路》 扫描二维码五折购书 为加强内网的安全防范&#xff0c;安全管理员往往会限制内网计算机访问互联网&#xff0c;当然不同机构的限制策略是不一样的&#xff0c;有的完全阻断了内网计算机访问…

【Linux】进程的优先级及linux下进程的调度于切换

目录 ​编辑 1.优先级是什么 2.linux中的优先级是怎么实现的 ps -la 命令查看当前用户启动的进程​编辑 linux下调整优先级&#xff1a; ①先top一下 ②点击r ③需要输入进程的pid ④回车 ​编辑 ⑤输入想将优秀级修改的值&#xff1a; linux进程优先级范围为什么必须是【60,9…

自编译支持CUDA硬解的OPENCV和FFMPEG

1 整体思路 查阅opencv的官方文档&#xff0c;可看到有个cudacodec扩展&#xff0c;用他可方便的进行编解码。唯一麻烦的是需要自行编译opencv。 同时&#xff0c;为了考虑后续方便&#xff0c;顺手编译了FFMPEG&#xff0c;并将其与OPENCV绑定。 在之前的博文“鲲鹏主机昇腾A…

osg场景图的数据结构

1、Scene Graph场景图 场景图是一种描述三维场景的数据结构:它是一个有向无循环图。 OSG中不仅定义了场景图的数据结构&#xff0c;还提供了对这种图数据结构的各种访问方式&#xff0c;或者说是管理方法&#xff0c;如渲染。 2、常见节点 备注&#xff1a;Tranform变换的是模…

小车项目介绍

STM32智能小车基于STM32F103C8T6进行开发 该项目具有OLED,USART串口,ADC测量电压,陀螺仪,超声波测距模块,红外循迹模块,蓝牙模块,按键,电机驱动,电机,舵机,电源等功能 功能详细介绍: OLED模块 使用:OLED显示屏模块 0.96寸 IIC/SPI 选择原因&#xff1a;价格较低、使用方便…

如何在jmeter中把响应中的数据提取出来并引用

jmeter做接口测试过程中&#xff0c;经常遇到请求需要用到token的时候&#xff0c;我们可以把返回token的接口用后置处理器提取出来&#xff0c;但是在这种情况下&#xff0c;只能适用于当前的线程组&#xff0c;其他线程组无法引用到提取的token变量值&#xff0c;所以必须要生…

如何用好PMP项目管理知识

PMP(Project Management Professional&#xff0c;项目管理专业人士)是由国际项目管理协会&#xff08;PMI&#xff09;颁发的全球最高级别的项目管理认证&#xff0c;认证需要通过严格的考试&#xff0c;并具备相应的工作经验和教育背景。 作为一名咨询师&#xff0c;我们经常…

vscode和pycharm等idea编写protobuf文件格式化

想在pycharm或者goland等idea中开发protobuf文件的话&#xff0c;可以安装一个插件&#xff1a;protocol-buffers 安装之后&#xff0c;proto文件就会支持高亮和格式化了。 如果是vscode想要编写proto文件&#xff0c;可以安装另外一个插件&#xff1a;vscode-proto3 安装后&a…

C++修炼之路之list模拟实现--C++中的双向循环链表

目录 引言 一&#xff1a;STL源代码中关于list的成员变量的介绍 二&#xff1a;模拟实现list 1.基本结构 2.普通迭代器 const迭代器的结合 3.构造拷贝构造析构赋值重载 清空 4.inserterase头尾插入删除 5.打印不同数据类型的数据《使用模板加容器来完成》 三&#xf…

AGI趋势/创业的从业者

红杉这两年分享了好多AI文章&#xff0c;收录了多篇关于GenAI的观点和文章&#xff0c;涉及GenAI的未来、趋势、应用和挑战等话题。 比如&#xff1a; 2024 年的人工智能&#xff1a;从大爆炸到原始汤 下一个十亿开发者 生成式人工智能的第二幕 AI 的 $200B 问题 将生成式…

2024 MathorCupC题完整解题及成品论文!

C 题 物流网络分拣中心货量预测及人员排班 电商物流网络在订单履约中由多个环节组成,图 1 是一个简化的物流 网络示意图。其中,分拣中心作为网络的中间环节,需要将包裹按照不同 流向进行分拣并发往下一个场地,最终使包裹到达消费者手中。分拣中心 管理效率的提升,对整体网络的…