0
  • 聊天消息
  • 系統(tǒng)消息
  • 評(píng)論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會(huì)員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識(shí)你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

HarmonyOS開發(fā)實(shí)例:【事件的訂閱和發(fā)布】

jf_46214456 ? 來(lái)源:jf_46214456 ? 作者:jf_46214456 ? 2024-04-15 17:36 ? 次閱讀

介紹

本示例主要展示了公共事件相關(guān)的功能,實(shí)現(xiàn)了一個(gè)檢測(cè)用戶部分行為的應(yīng)用。具體而言實(shí)現(xiàn)了如下幾點(diǎn)功能:

1.通過(guò)訂閱系統(tǒng)公共事件,實(shí)現(xiàn)對(duì)用戶操作行為(亮滅屏、鎖屏和解鎖屏幕、斷聯(lián)網(wǎng))的監(jiān)測(cè);

2.通過(guò)在用戶主動(dòng)停止監(jiān)測(cè)行為時(shí)發(fā)布自定義有序公共事件,實(shí)現(xiàn)對(duì)用戶主動(dòng)觸發(fā)監(jiān)聽行為的持久化記錄;

3.通過(guò)在用戶設(shè)置對(duì)某一事件的監(jiān)聽狀態(tài)時(shí)發(fā)布粘性事件,記錄下本次應(yīng)用運(yùn)行期間允許監(jiān)聽的事件列表,同時(shí)在應(yīng)用退出時(shí)將臨時(shí)允許的修改為不允許;

4.打開自定義訂閱事件頁(yè)面需先安裝[CardEvent]應(yīng)用,通過(guò)訂閱指定應(yīng)用事件,實(shí)現(xiàn)用戶對(duì)指定卡片發(fā)送事件的監(jiān)聽。

效果預(yù)覽

訂閱系統(tǒng)公共事件,主動(dòng)停止監(jiān)聽行為及對(duì)某一事件的監(jiān)聽狀態(tài)時(shí)發(fā)布粘性事件

image.png

使用說(shuō)明:鴻蒙開發(fā)文檔參考了[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md]點(diǎn)擊或者復(fù)制轉(zhuǎn)到即可。

1.安裝編譯生成的hap包,依賴包hap,桌面上顯示應(yīng)用圖標(biāo)如下,點(diǎn)擊圖標(biāo)即可進(jìn)入應(yīng)用。

image.png

2.進(jìn)入應(yīng)用顯示菜單頁(yè),可選擇“進(jìn)入”,“歷史”,“設(shè)置”及“關(guān)于”幾個(gè)選項(xiàng)。

3.點(diǎn)擊“進(jìn)入”后跳轉(zhuǎn)至主頁(yè)面,點(diǎn)擊主頁(yè)面“開始監(jiān)控”按鈕,將開始監(jiān)聽系統(tǒng)公共事件,并進(jìn)行計(jì)時(shí),此時(shí)按鈕內(nèi)容變更為“停止監(jiān)聽”;點(diǎn)擊停止監(jiān)聽按鈕,頁(yè)面上將顯示本次監(jiān)聽時(shí)長(zhǎng)及監(jiān)聽期間收到的干擾信息匯總,并在頁(yè)面右下角顯示“查看詳情”按鈕,點(diǎn)擊按鈕將跳轉(zhuǎn)至詳情頁(yè),顯示監(jiān)聽期間收到的干擾信息,應(yīng)用當(dāng)前僅監(jiān)聽了亮滅屏、鎖屏和解鎖屏幕、斷聯(lián)網(wǎng)等用戶可操作的系統(tǒng)公共事件,后續(xù)可根據(jù)需求快速擴(kuò)展。

4.返回至應(yīng)用菜單頁(yè)面,點(diǎn)擊“歷史”可查看用戶操作監(jiān)聽的歷史記錄,當(dāng)前支持每次運(yùn)行期間最多存儲(chǔ)10條歷史記錄,超過(guò)10條后將刪除歷史數(shù)據(jù)。

5.返回至應(yīng)用菜單頁(yè)面,點(diǎn)擊“設(shè)置”可進(jìn)行具體系統(tǒng)事件的監(jiān)聽配置,應(yīng)用提供了“一直”、“僅本次”及“從不”三個(gè)選項(xiàng),其中“僅本次”選項(xiàng)是指本次應(yīng)用運(yùn)行期間將監(jiān)聽特定系統(tǒng)公共事件,應(yīng)用退出后該選項(xiàng)將自動(dòng)調(diào)整為“從不”。

6.在設(shè)置頁(yè)面,點(diǎn)擊“自定義事件定向訂閱”進(jìn)入訂閱頁(yè)面,

  • 點(diǎn)擊”訂閱“按鈕進(jìn)行訂閱事件,同時(shí)訂閱指定本應(yīng)用事件和訂閱非指定應(yīng)用事件。
  • 點(diǎn)擊應(yīng)用內(nèi)卡片發(fā)送事件或點(diǎn)擊應(yīng)用外卡片發(fā)送事件。
  • 點(diǎn)擊應(yīng)用內(nèi)卡片發(fā)送事件后,指定應(yīng)用事件和非指定應(yīng)用事件均會(huì)接收到卡片所發(fā)送的事件 ;點(diǎn)擊應(yīng)用外卡片發(fā)送事件后,非指定應(yīng)用事件會(huì)被接收,指定應(yīng)用事件不會(huì)被接收。
  • 點(diǎn)擊”取消訂閱“ 頁(yè)面中會(huì)提示當(dāng)前事件取消訂閱。

7.返回至應(yīng)用菜單頁(yè)面,點(diǎn)擊“關(guān)于”可查看應(yīng)用版本信息及本示例的說(shuō)明。

搜狗高速瀏覽器截圖20240326151547.png

代碼解讀

CustomCommonEvent

HarmonyOSOpenHarmony開發(fā)文檔+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                            // 數(shù)據(jù)定義
|   |---Logger.ts                            // 日志打印  
|   |---SurveillanceEventsManager.ts         // 公共事件模塊
|   |---Utils.ts                        
|---pages
|   |---About.ets                            // 關(guān)于頁(yè)面
|   |---Detail.ets                           // 詳情頁(yè)面
|   |---History.ets                          // 歷史頁(yè)面
|   |---jumpToCommonEvent.ets                // 自定義訂閱事件頁(yè)面
|   |---Launch.ets                           // 發(fā)起頁(yè)面
|   |---Main.ets                             // 進(jìn)入頁(yè)面
|   |---Setting.ets                          // 設(shè)置頁(yè)面
|---publishcard
|   |---pages
|   |	|---PublishCard.ets              	 // 卡片頁(yè)面

CustomCommonEventRely

entry/src/main/ets/
|---entryformability
|   |---EntryFormAbility.ts					// 發(fā)布事件
|---pages
|   |---Index.ets
|---widget
|   |---pages
|   |	|---PublishCard.ets 				// 發(fā)布事件的卡片

具體實(shí)現(xiàn)

  • 該示例entry部分分為五個(gè)模塊:
    • 進(jìn)入模塊
      • 使用到應(yīng)用文上下文,createSubscriber方法創(chuàng)建訂閱者,getCurrentTime獲取獲取自Unix紀(jì)元以來(lái)經(jīng)過(guò)的時(shí)間進(jìn)行對(duì)用戶操作行為的監(jiān)測(cè)功能頁(yè)面開發(fā)。
  • 源碼鏈接:[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]
    • 歷史模塊
      • 使用到應(yīng)用文上下文,getPreferences方法獲取Preferences實(shí)例,組件Header進(jìn)行歷史頁(yè)面開發(fā)。
  • 源碼鏈接:[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]
    • 設(shè)置模塊
      • 本模塊分為三個(gè)事件,分別為記錄聯(lián)網(wǎng)事件,記錄滅屏事件,記錄亮屏事件,進(jìn)行鎖屏事件、進(jìn)行解鎖屏幕事件,每一個(gè)事件都可進(jìn)行一直,僅本次和從不的單項(xiàng)選擇,使用到應(yīng)用文上下文嗎,CommonEvent.publish發(fā)布公共事件,getPreferences方法獲取Preferences實(shí)例進(jìn)行功能頁(yè)面開發(fā)。
      • 源碼鏈接:[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]
    • 關(guān)于模塊

      • 該模塊開發(fā)主要介紹了本示例的功能作用以及說(shuō)明了什么情況下不能使用。
      • 源碼鏈接:[Header.ets],[Consts.ts]
    • 設(shè)置中訂閱事件模塊

      • 本模塊主要支持指定應(yīng)用訂閱自定義事件。subScribeInfo新增可選屬性publisherBundleName,創(chuàng)建訂閱對(duì)象時(shí)可指定PublisherBundlerName,事件發(fā)布時(shí),獲取訂閱者信息,增加校驗(yàn)bundleName是否等于publisherBundlerName,相等則加入事件回調(diào)方,達(dá)成只接收指定發(fā)布方發(fā)布的事件的效果。
      • 源碼鏈接:[EntryFormAbility.ts],[PublishCard.ets]
      • 參考接口:[@ohos.commonEventManager],[@ohos.hilog],[@ohos.app.form.formInfo],[@ohos.app.form.formBindingData],[@ohos.app.form.FormExtensionAbility]

審核編輯 黃宇

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場(chǎng)。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問(wèn)題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • 鴻蒙
    +關(guān)注

    關(guān)注

    57

    文章

    2351

    瀏覽量

    42849
  • HarmonyOS
    +關(guān)注

    關(guān)注

    79

    文章

    1975

    瀏覽量

    30182
收藏 人收藏

    評(píng)論

    相關(guān)推薦

    RabbitMQ中的發(fā)布訂閱模型

    上一篇文章中,簡(jiǎn)單的介紹了一下RabbitMQ的work模型。這篇文章來(lái)學(xué)習(xí)一下RabbitMQ中的發(fā)布訂閱模型。 發(fā)布訂閱模型(Publish/Subscribe):簡(jiǎn)單的說(shuō)就是隊(duì)列
    的頭像 發(fā)表于 09-25 14:30 ?524次閱讀
    RabbitMQ中的<b class='flag-5'>發(fā)布</b><b class='flag-5'>訂閱</b>模型

    HarmonyOS開發(fā)實(shí)例:【自定義Emitter】

    使用[Emitter]實(shí)現(xiàn)事件的訂閱發(fā)布,使用[自定義彈窗]設(shè)置廣告信息。
    的頭像 發(fā)表于 04-14 11:37 ?1002次閱讀
    <b class='flag-5'>HarmonyOS</b><b class='flag-5'>開發(fā)</b><b class='flag-5'>實(shí)例</b>:【自定義Emitter】

    基于ArkTS語(yǔ)言的OpenHarmony APP應(yīng)用開發(fā):公共事件的訂閱發(fā)布

    應(yīng)用程序提供訂閱發(fā)布、退訂公共事件的能力。 公共事件從系統(tǒng)角度可分為:系統(tǒng)公共事件和自定義公共事件。 系統(tǒng)公共事件:CES內(nèi)部定義的公共事件,只有系統(tǒng)應(yīng)用和系統(tǒng)服務(wù)才能發(fā)布,例如HAP安裝,更新,卸載
    發(fā)表于 09-18 13:16

    MQTT協(xié)議介紹之一:發(fā)布/訂閱

    MQTT協(xié)議的內(nèi)容。這里先介紹MQTT信息和協(xié)議背景。MQTT介紹MQTT是客戶端服務(wù)器發(fā)布/訂閱消息傳輸協(xié)議,它重量輕,開放,簡(jiǎn)單,設(shè)計(jì)好,易于實(shí)施,這些特性使其成為在許多情況下的理想選擇,包括了受限
    發(fā)表于 08-25 19:58

    Redis的發(fā)布訂閱機(jī)制

    Redis之發(fā)布訂閱機(jī)制
    發(fā)表于 06-11 13:21

    HarmonyOS應(yīng)用開發(fā)-編譯、調(diào)試、應(yīng)用發(fā)布資料

    Studio提供了基于各種編寫代碼及不同設(shè)備的調(diào)試功能,如果使用了多種代碼編寫應(yīng)用,請(qǐng)參考選擇調(diào)試代碼類型進(jìn)行配置后啟動(dòng)調(diào)試,調(diào)試過(guò)程中基于不同的代碼進(jìn)行斷點(diǎn)管理。開發(fā)者完成HarmonyOS應(yīng)用開發(fā)
    發(fā)表于 09-21 16:29

    HarmonyOS初步探索系列文章匯總

    DevEco Studio是基于IntelliJ IDEA社區(qū)的開源版本打造,面向華為終端全場(chǎng)景多設(shè)備的一站式集成開發(fā)環(huán)境(IDE),為開發(fā)者提供工程模板創(chuàng)建,開發(fā),編譯,調(diào)試和發(fā)布
    發(fā)表于 12-15 14:56

    重磅!HarmonyOS 2.0正式發(fā)布:Firefly與華為計(jì)劃推出RK3399 HarmonyOS 2.0開發(fā)套件

    ,10.1寸多觸摸顯示屏等整體硬件,一站式解決了開發(fā)者對(duì)硬件平臺(tái)的選擇與適配的問(wèn)題。HarmonyOS2.0發(fā)布后,F(xiàn)irefly會(huì)繼續(xù)深入HarmonyOS的生態(tài)。除了“
    發(fā)表于 06-03 13:59

    絕對(duì)干貨!HarmonyOS開發(fā)者日資料全公開,鴻蒙開發(fā)者都在看

    的在線教育內(nèi)容和小游戲快速適配發(fā)布HarmonyOS平臺(tái)的遷移方案。5、HarmonyOS 開發(fā)平臺(tái)和工具:該主題介紹了HarmonyOS
    發(fā)表于 08-04 14:36

    NodeMCU實(shí)現(xiàn)訂閱發(fā)布主題

    NodeMCU實(shí)現(xiàn)訂閱發(fā)布主題。1、要點(diǎn)掃盲1.1 MQTT《MQTT協(xié)議--MQTT協(xié)議簡(jiǎn)介及原理》《MQTT協(xié)議--MQTT協(xié)議解析》1.2 OneNET《NodeMCU學(xué)習(xí)(十)--發(fā)送數(shù)據(jù)
    發(fā)表于 11-01 08:37

    新一期HarmonyOS認(rèn)證正式發(fā)布,速來(lái)圍觀!

    華為認(rèn)證HarmonyOS應(yīng)用開發(fā)高級(jí)工程師HCIP-HarmonyOS Application Developer V1.0(中文版)自2022年05月30日起,正式在中國(guó)區(qū)發(fā)布。
    發(fā)表于 06-06 19:17

    面向開發(fā)者的HarmonyOS 3.0 Beta發(fā)布

    2021年10月,我們面向開發(fā)發(fā)布HarmonyOS 3.0 Developer Preview版,但開發(fā)的腳步永不停歇,現(xiàn)在我們又更新了API版本,配套
    發(fā)表于 07-08 11:14

    HarmonyOS 3.1版本發(fā)布,全面進(jìn)入聲明式開發(fā)

    開發(fā)者的腳步永不停歇,2022年我們發(fā)布HarmonyOS 3.0 Release版本,為了進(jìn)一步滿足開發(fā)者高效開發(fā)應(yīng)用程序的訴求,在同年
    發(fā)表于 11-15 11:58

    HarmonyOS遠(yuǎn)端狀態(tài)訂閱開發(fā)實(shí)例

    IPC/RPC提供對(duì)遠(yuǎn)端Stub對(duì)象狀態(tài)的訂閱機(jī)制, 在遠(yuǎn)端Stub對(duì)象消亡時(shí),可觸發(fā)消亡通知告訴本地Proxy對(duì)象。這種狀態(tài)通知訂閱需要調(diào)用特定接口完成,當(dāng)不再需要訂閱時(shí)也需要調(diào)用特定接口取消
    發(fā)表于 10-12 14:55

    面向HarmonyOS開發(fā)者的HarmonyOS 3.0 Beta介紹

    2021年10月,我們面向開發(fā)發(fā)布HarmonyOS 3.0 Developer Preview版,但開發(fā)的腳步永不停歇,現(xiàn)在我們又更新了API版本,配套
    的頭像 發(fā)表于 07-06 20:34 ?3308次閱讀