介紹
本示例主要展示了公共事件相關的功能,實現了一個檢測用戶部分行為的應用。具體而言實現了如下幾點功能:
1.通過訂閱系統公共事件,實現對用戶操作行為(亮滅屏、鎖屏和解鎖屏幕、斷聯網)的監測;
2.通過在用戶主動停止監測行為時發布自定義有序公共事件,實現對用戶主動觸發監聽行為的持久化記錄;
3.通過在用戶設置對某一事件的監聽狀態時發布粘性事件,記錄下本次應用運行期間允許監聽的事件列表,同時在應用退出時將臨時允許的修改為不允許;
4.打開自定義訂閱事件頁面需先安裝[CardEvent]應用,通過訂閱指定應用事件,實現用戶對指定卡片發送事件的監聽。
效果預覽
訂閱系統公共事件,主動停止監聽行為及對某一事件的監聽狀態時發布粘性事件
使用說明:鴻蒙開發文檔參考了[gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md
]點擊或者復制轉到即可。
1.安裝編譯生成的hap包,依賴包hap,桌面上顯示應用圖標如下,點擊圖標即可進入應用。
2.進入應用顯示菜單頁,可選擇“進入”,“歷史”,“設置”及“關于”幾個選項。
3.點擊“進入”后跳轉至主頁面,點擊主頁面“開始監控”按鈕,將開始監聽系統公共事件,并進行計時,此時按鈕內容變更為“停止監聽”;點擊停止監聽按鈕,頁面上將顯示本次監聽時長及監聽期間收到的干擾信息匯總,并在頁面右下角顯示“查看詳情”按鈕,點擊按鈕將跳轉至詳情頁,顯示監聽期間收到的干擾信息,應用當前僅監聽了亮滅屏、鎖屏和解鎖屏幕、斷聯網等用戶可操作的系統公共事件,后續可根據需求快速擴展。
4.返回至應用菜單頁面,點擊“歷史”可查看用戶操作監聽的歷史記錄,當前支持每次運行期間最多存儲10條歷史記錄,超過10條后將刪除歷史數據。
5.返回至應用菜單頁面,點擊“設置”可進行具體系統事件的監聽配置,應用提供了“一直”、“僅本次”及“從不”三個選項,其中“僅本次”選項是指本次應用運行期間將監聽特定系統公共事件,應用退出后該選項將自動調整為“從不”。
6.在設置頁面,點擊“自定義事件定向訂閱”進入訂閱頁面,
- 點擊”訂閱“按鈕進行訂閱事件,同時訂閱指定本應用事件和訂閱非指定應用事件。
- 點擊應用內卡片發送事件或點擊應用外卡片發送事件。
- 點擊應用內卡片發送事件后,指定應用事件和非指定應用事件均會接收到卡片所發送的事件 ;點擊應用外卡片發送事件后,非指定應用事件會被接收,指定應用事件不會被接收。
- 點擊”取消訂閱“ 頁面中會提示當前事件取消訂閱。
7.返回至應用菜單頁面,點擊“關于”可查看應用版本信息及本示例的說明。
代碼解讀
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]
審核編輯 黃宇
-
鴻蒙
+關注
關注
57文章
2351瀏覽量
42849 -
HarmonyOS
+關注
關注
79文章
1975瀏覽量
30183
發布評論請先 登錄
相關推薦
評論