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

news2025/2/6 0:51:23

介绍

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

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 database

  static 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 state

  static readonly ENABLE_STATE_ALWAYS : number = 0

  static readonly ENABLE_STATE_ONCE : number = 1

  static readonly ENABLE_STATE_NEVER : number = 2



  // definition for record volume

  static readonly MAX_RECORD_NUM: number = 10;



  // definition for self defined common events

  static 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 database

    this.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 = () => {

    // subscribe

    if (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 = subscriber

        if (subscriber != null) {

          commonEvent.subscribe(subscriber, this.callbackFunc)

        }

      });

    }

    // subscribe

    if (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 = subscriber

        if (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 ability

    windowStage.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 resources

    Logger.info("LauncherAbility onWindowStageDestroy");

  }



  onForeground() {

    // Ability has brought to foreground

    Logger.info("LauncherAbility onForeground");

  }



  onBackground() {

    // Ability has back to background

    Logger.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'



@Component

export 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 database

  static 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 state

  static readonly ENABLE_STATE_ALWAYS : number = 0

  static readonly ENABLE_STATE_ONCE : number = 1

  static readonly ENABLE_STATE_NEVER : number = 2



  // definition for record volume

  static readonly MAX_RECORD_NUM: number = 10;



  // definition for self defined common events

  static 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 = null

    await 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 = null

  private pref: dataPreferences.Preferences = null



  constructor(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.coloradmin.cn/o/1598818.html

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

相关文章

Navigator.share不生效,请检查是不是https,仅在https中可用

mdn 一定要检查mdn的兼容性&#xff0c;和是否是https&#xff0c;http中是不生效的&#xff0c;但是测试的时候ios Safari可以chrome就不行&#xff0c;但是https就能够稳定运行

英语新概念2-回译法-lesson8

乔桑德斯有着我们镇上最漂亮的花园。附近的每一个人每年都参加“最美花园比赛”&#xff0c;但是每年都是乔赢得比赛。比尔芙丽丝的花园比乔的花园大&#xff0c;但是乔的花园更有趣。他有整洁的小径以及一座木桥架在一个池塘上。我也喜欢花园&#xff0c;但是我不喜欢辛勤劳作…

LeetCode 热题100(python)——1

解题方案 解法一 class Solution:def twoSum(self, nums: List[int], target: int) -> List[int]:for i, x in enumerate(nums): # xnums[i]for j in range(i 1, len(nums)): # 枚举 i 右边的 jif x nums[j] target: # 满足要求return [i, j] # 返回两个数的下标# 这…

HarmonyOS实战开发-如何实现文件管理相关的功能。

介绍 本示例主要展示了文件管理相关的功能&#xff0c;使用ohos.multimedia.medialibrary 、ohos.filemanagement.userFileManager 、ohos.fileio 、ohos.file.fs、ohos.app.ability.contextConstant 等接口&#xff0c;实现了增添文件、删除文件、查找指定类型文件文件、复制…

electron项目打包慢、打包报错

项目使用了electron框架&#xff0c;在第一次打包或者网络条件不好的环境下进行打包时熟速度慢的出奇&#xff0c;甚至经常出现打包失败的情况&#xff08;如上面图片的报错&#xff09;。 这是因为&#xff0c;在electron打包的过程中&#xff0c;需要去官方源https://github.…

微信小程序英文版:实现一键切换中英双语版(已组件化)

已经重新优化代码做成了组件&#xff0c;需要可自取&#xff1a;https://github.com/CrystalCAI11/wechat-language-compoment 所有操作都打包在组件里不需要在额外的地方添加代码&#xff0c;直接在你需要的页面里导入组件&#xff0c;再在对应页面的onLoad()里set文本就行了。…

电压比较器LM339介绍和仿真

电压比较器LM339介绍和仿真 &#x1f4d1;LM339相关特性 工作电源电压范围宽&#xff0c;单电源、双电源均可工作&#xff0c;单电源&#xff1a; 2&#xff5e;36V&#xff0c;双电源&#xff1a;1&#xff5e;18V&#xff1b;消耗电流小&#xff0c; Icc1.3mA&#xff1b;输…

用二进制译码器实现组合逻辑函数

用二进制译码器实现组合逻辑函数 原理 由于 n n n 位二进制译码器可提供 2 n 2^n 2n 个最小项的输出&#xff0c;而任一个逻辑函数都可变换为最小项之和的标准与或式&#xff0c;因此利用译码器和门电路可实现单输出及多输出组合逻辑电路 基本步骤 选择合适的集成二进制译…

怎么做预约功能_让服务变得更便捷

在快节奏的现代生活中&#xff0c;时间成为了我们最宝贵的财富。无论是工作、学习还是休闲娱乐&#xff0c;我们都希望能够更加高效地利用每一分每一秒。而预约功能的出现&#xff0c;正是为了满足这一需求&#xff0c;让我们的生活变得更加便捷、高效。 工具/原料 微信小程序…

网络协议安全:SSL/TLS协议详解,SSL协议执行原理、报文格式解析,Wireshark抓包分析SSL协议

「作者简介」&#xff1a;2022年北京冬奥会中国代表队&#xff0c;CSDN Top100&#xff0c;学习更多干货&#xff0c;请关注专栏《网络安全自学教程》 SSL协议 1、SSL协议发展史2、SSL协议执行过程3、SSL报文格式字段解析3.1、TLS报文头3.2、Handshake报文 4、Wireshark抓包分析…

【Java开发指南 | 第三篇】Java 空行、强制类型转换及基本数据类型

读者可订阅专栏&#xff1a;Java开发指南 |【CSDN秋说】 文章目录 Java 空行强制类型转换Java 基本数据类型内置数据类型引用类型 Java 空行 空白行或者有注释的行&#xff0c;Java 编译器都会忽略掉。 强制类型转换 当需要将一个数据类型转换为另一个数据类型时&#xff0c…

DBA面试总结(Mysql篇)

一、delete与trancate的区别 相同点 1.两者都是删除表中的数据&#xff0c;不删除表结构 不同点 1.delete支持按条件删除&#xff0c;TRUNCATE不支持。 2.delete 删除后自增列不会重置&#xff0c;而TRUNCATE会被重置。 3.delete是逐条删除&#xff08;速度较慢&#xff09…

java:多线程中的死锁

多线程:死锁 当多个线程互相争抢资源导致都在互相等待资源的僵局时,如果没有外力,将会一直僵持下去,这就是死锁. 就像两个人分一双筷子,如果一人拿到一根筷子,都在等待对方手里的那根,将没有人能完成吃饭的任务. 死锁的必要条件 1,互斥 即资源只能被一个线程调用 2,不可剥…

STL的stack和queue(三):基于适配器模式的反向迭代器

目录 前言 list的反向迭代器 list.h文件 ReverseIterator.h文件 test.cpp文件 前言 迭代器按性质分类&#xff1a; 单向&#xff1a;forward_list双向&#xff1a;list随机&#xff1a;vector / deque 迭代器按功能分类&#xff1a; 正向反向const list的反向迭代器…

【Redis 神秘大陆】001 背景基础理论

一、背景&基础理论 1.1 什么是缓存 缓存&#xff1a;存储在计算机上的一个原始数据复制集&#xff0c;以便于访问——维基百科 1.2 为什么用缓存 提升用户体验&#xff1a; 【即效率、效益和基本主观满意度】CAST 使用者的状态、系统性能及环境&#xff0c;不同的人对于…

(最新)华为 2024 届实习招聘-硬件通⽤/单板开发——第十一套和十二套

&#xff08;最新&#xff09;华为 2024 届实习招聘-硬件通⽤/单板开发——第十一套和十二套 部分题目分享&#xff0c;完整版带答案(有答案和解析&#xff0c;答案非官方&#xff0c;未仔细校正&#xff0c;仅供参考&#xff09;&#xff08;共十套&#xff09;获取&#xff…

InnoDB架构:内存篇

InnoDB架构&#xff1a;内存篇 InnoDB是MySQL数据库中默认的存储引擎&#xff0c;它为数据库提供了事务安全型&#xff08;ACID兼容&#xff09;、行级锁定和外键支持等功能。InnoDB的架构设计优化了对于读取密集和写入密集型应用的性能表现&#xff0c;是一个高度优化的存储系…

逆向IDA中Dword,数据提取

我们可以看见数据是这样的&#xff0c;第一个是1cc 但是我们shifte就是 这个因为他的数据太大了&#xff0c;导致高位跑后面去了 这个时候&#xff0c;我们右键——convert——dword 这样就可以提取到争取的数据了 比如第一个数据 0x1cc a0xcc b0x1 print(hex((b<<8…

李沐25_使用块的网络VGG——自学笔记

VGG架构 1.多个VGG块后接全连接层 2.不同次数的重复块得到不同的架构 VGG-16、VGG-19 3.更大更深的AlexNet ##经典卷积神经网络的基本组成部分是下面的这个序列&#xff1a; 1.带填充以保持分辨率的卷积层&#xff1b; 2.非线性激活函数&#xff0c;如ReLU&#xff1b; …

zabbix升级后图形文字不显示

原版本升级后版本6.4.76.4.13 问题现象 更新小版本后zabbix数据图形都有&#xff0c;只有下方文字不显示 处理方式 下载win字体&#xff0c;根据自己选择&#xff0c;上传至/usr/share/zabbix/assets/fonts目录下&#xff0c;修改文件名为jianti.ttf 修改默认字体配置文件…