公共事件的订阅和发布
介绍
本示例主要展示了公共事件相关的功能,实现了一个检测用户部分行为的应用。具体而言实现了如下几点功能:
1.通过订阅系统公共事件,实现对用户操作行为(亮灭屏、锁屏和解锁屏幕、断联网)的监测;
2.通过在用户主动停止监测行为时发布自定义有序公共事件,实现对用户主动触发监听行为的持久化记录;
3.通过在用户设置对某一事件的监听状态时发布粘性事件,记录下本次应用运行期间允许监听的事件列表,同时在应用退出时将临时允许的修改为不允许。
效果预览
使用说明:
1.安装编译生成的hap包,桌面上显示应用图标如下,点击图标即可进入应用。
2.进入应用显示菜单页,可选择“进入”,“历史”,“设置”及“关于”几个选项。
3.点击“进入”后跳转至主页面,点击主页面“开始监控”按钮,将开始监听系统公共事件,并进行计时,此时按钮内容变更为“停止监听”;点击停止监听按钮,页面上将显示本次监听时长及监听期间收到的干扰信息汇总,并在页面右下角显示“查看详情”按钮,点击按钮将跳转至详情页,显示监听期间收到的干扰信息,应用当前仅监听了亮灭屏、锁屏和解锁屏幕、断联网等用户可操作的系统公共事件,后续可根据需求快速扩展。
4.返回至应用菜单页面,点击“历史”可查看用户操作监听的历史记录,当前支持每次运行期间最多存储10条历史记录,超过10条后将删除历史数据。
5.返回至应用菜单页面,点击“设置”可进行具体系统事件的监听配置,应用提供了“一直”、“仅本次”及“从不”三个选项,其中“仅本次”选项是指本次应用运行期间将监听特定系统公共事件,应用退出后该选项将自动调整为“从不”。
6.返回至应用菜单页面,点击“关于”可查看应用版本信息及本示例的说明。
具体实现
-
该示例分为四个模块:
-
进入模块
- 使用到应用文上下文,createSubscriber方法创建订阅者,getCurrentTime获取获取自Unix纪元以来经过的时间进行对用户操作行为的监测功能页面开发。
- 源码参考:[Consts.ets]
-
/*
* 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 { commonEventManager } from '@kit.BasicServicesKit';
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 = commonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE;
static readonly DATA_BASE_KEY_SCREEN_OFF: string = commonEventManager.Support.COMMON_EVENT_SCREEN_OFF;
static readonly DATA_BASE_KEY_SCREEN_ON: string = commonEventManager.Support.COMMON_EVENT_SCREEN_ON;
static readonly DATA_BASE_KEY_SCREEN_LOCKED: string = commonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED;
static readonly DATA_BASE_KEY_SCREEN_UNLOCKED: string = commonEventManager.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.ets]
/*
* 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 '@kit.AbilityKit';
import { commonEventManager, BusinessError } from '@kit.BasicServicesKit';
import consts from '../module/Consts';
import { preferences } from '@kit.ArkData';
import Logger from '../module/Logger';
import { router } from '@kit.ArkUI';
import { Want } from '@kit.AbilityKit';
import { GlobalContext } from '../module/GlobalContext';
export default class LaunchFeature {
private innerContext: common.UIAbilityContext | null = null;
private pref: preferences.Preferences | null = null;
private subscriber: commonEventManager.CommonEventSubscriber | null = null;
private subscriberLow: commonEventManager.CommonEventSubscriber | null = null;
private currentRecordTimes: number = 0;
constructor(abilityContext: common.UIAbilityContext) {
this.innerContext = abilityContext;
}
async init(): Promise<void> {
await preferences.getPreferences(this.innerContext as common.UIAbilityContext, consts.DATA_BASE_NAME)
.then((pref) => {
this.pref = pref;
});
await this.pref?.get(consts.DATA_BASE_KEY_WIFI_POWER_STATE, 0).then((value: preferences.ValueType) => {
(GlobalContext.getContext()
.getObject('settings') as Map<string, number>).set(commonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE, value as number);
});
await this.pref?.get(consts.DATA_BASE_KEY_SCREEN_OFF, 0).then((value1: preferences.ValueType) => {
(GlobalContext.getContext()
.getObject('settings') as Map<string, number>).set(commonEventManager.Support.COMMON_EVENT_SCREEN_OFF, value1 as number);
});
await this.pref?.get(consts.DATA_BASE_KEY_SCREEN_ON, 0).then((value2: preferences.ValueType) => {
(GlobalContext.getContext()
.getObject('settings') as Map<string, number>).set(commonEventManager.Support.COMMON_EVENT_SCREEN_ON, value2 as number);
});
await this.pref?.get(consts.DATA_BASE_KEY_SCREEN_LOCKED, 0).then((value3: preferences.ValueType) => {
(GlobalContext.getContext()
.getObject('settings') as Map<string, number>).set(commonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED, value3 as number);
});
await this.pref?.get(consts.DATA_BASE_KEY_SCREEN_UNLOCKED, 0).then((value4: preferences.ValueType) => {
(GlobalContext.getContext()
.getObject('settings') as Map<string, number>).set(commonEventManager.Support.COMMON_EVENT_SCREEN_UNLOCKED, value4 as number);
});
}
private insertRecord = (event: commonEventManager.CommonEventData, value: preferences.ValueType) => {
if (event.parameters) {
(value as Array<string>).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> = [];
if (event.parameters) {
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: BusinessError, event: commonEventManager.CommonEventData) => {
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: BusinessError, event: commonEventManager.CommonEventData) => {
this.currentRecordTimes = 1;
this.pref?.get(consts.DATA_BASE_KEY_TOTAL_TIMES, []).then((value: preferences.ValueType) => {
for (let i = 0; i < consts.MAX_RECORD_NUM; i++) {
this.pref?.delete((value as Array<string>)[i]).then(() => {
this.pref?.flush();
this.subscriberLow?.finishCommonEvent();
})
}
let records = (value as Array<string>).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: commonEventManager.CommonEventSubscribeInfo = {
events: [
consts.COMMON_EVENT_FINISH_MEDITATION// unordered self defined event
],
priority: 2 // 2 indicates high priority subscriber
};
commonEventManager.createSubscriber(highSubscriberInfo, (err, subscriber) => {
this.subscriber = subscriber
if (subscriber != null) {
commonEventManager.subscribe(subscriber, this.callbackFunc);
}
});
}
// subscribe
if (this.subscriberLow == null) {
let lowSubscriberInfo: commonEventManager.CommonEventSubscribeInfo = {
events: [
consts.COMMON_EVENT_FINISH_MEDITATION// unordered self defined event
],
priority: 1 // 1 indicates low priority subscriber
};
commonEventManager.createSubscriber(lowSubscriberInfo, (err, subscriber) => {
this.subscriberLow = subscriber;
if (subscriber != null) {
commonEventManager.subscribe(subscriber, this.callbackLowFunc);
}
});
}
let want: 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: {}
});
}
}
- 源码参考:[LauncherAbility.ets]
/*
* 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 { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
import { commonEventManager } from '@kit.BasicServicesKit';
import consts from '../module/Consts';
import { preferences } from '@kit.ArkData';
import surveillanceEventsManager from '../module/SurveillanceEventsManager';
import { window } from '@kit.ArkUI';
import Logger from '../module/Logger';
import { GlobalContext } from '../module/GlobalContext';
export default class LauncherAbility extends UIAbility {
onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
GlobalContext.getContext().setObject('abilityWant', want);
let settings: Map<string, number> = new Map();
surveillanceEventsManager.surveillanceEvents.forEach((element: string) => {
settings.set(element, consts.ENABLE_STATE_ALWAYS);
});
GlobalContext.getContext().setObject('settings', settings);
let curSettings = GlobalContext.getContext().getObject('settings') as Map<string, number>;
Logger.info(`LauncherAbility onCreate, settings.size = ${curSettings.size}`);
}
async onDestroy() {
Logger.info("LauncherAbility onDestroy");
(GlobalContext.getContext().getObject('settings') as Map<string, number>)
.forEach((value: number, key: string) => {
if (value == consts.ENABLE_STATE_ONCE) {
(GlobalContext.getContext().getObject('settings') as Map<string, number>).set(key, consts.ENABLE_STATE_NEVER);
}
});
let thisPref: preferences.Preferences | null = null;
await preferences.getPreferences(this.context, consts.DATA_BASE_NAME).then((pref) => {
thisPref = pref;
});
for (let element of surveillanceEventsManager.surveillanceEvents) {
await thisPref!.put(element, (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(element));
}
;
await thisPref!.flush();
let options: commonEventManager.CommonEventPublishData = {
isSticky: true,
parameters: surveillanceEventsManager.getSurveillanceEventStates()
};
commonEventManager.publish(consts.COMMON_EVENT_SETTING_UPDATE, options, () => {
Logger.info("success to publish once enable event");
});
}
onWindowStageCreate(windowStage: window.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.ets]
/*
* 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 { commonEventManager } from '@kit.BasicServicesKit';
import { GlobalContext } from './GlobalContext';
export default class SurveillanceEventsManager {
constructor() {
}
static getSurveillanceEventStates(): Record<string, number> {
return {
"usual.event.wifi.POWER_STATE": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE) as number,
"usual.event.SCREEN_OFF": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_SCREEN_OFF) as number,
"usual.event.SCREEN_ON": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_SCREEN_ON) as number,
"usual.event.SCREEN_LOCKED": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED) as number,
"usual.event.SCREEN_UNLOCKED": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_SCREEN_UNLOCKED) as number
}
}
static surveillanceEvents: Array<string> = [
commonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE,
commonEventManager.Support.COMMON_EVENT_SCREEN_OFF,
commonEventManager.Support.COMMON_EVENT_SCREEN_ON,
commonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED,
commonEventManager.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 '@kit.ArkUI';
@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.ets]
/*
* 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 { commonEventManager } from '@kit.BasicServicesKit';
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 = commonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE;
static readonly DATA_BASE_KEY_SCREEN_OFF: string = commonEventManager.Support.COMMON_EVENT_SCREEN_OFF;
static readonly DATA_BASE_KEY_SCREEN_ON: string = commonEventManager.Support.COMMON_EVENT_SCREEN_ON;
static readonly DATA_BASE_KEY_SCREEN_LOCKED: string = commonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED;
static readonly DATA_BASE_KEY_SCREEN_UNLOCKED: string = commonEventManager.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.ets]
/*
* 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 '@kit.AbilityKit';
import consts from '../module/Consts';
import { preferences } from '@kit.ArkData';
import Logger from '../module/Logger';
import { BusinessError } from '@kit.BasicServicesKit';
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<string[][]>((resolve) => {
resolve(this.dataSource);
})
}
private async init() {
let prefer: preferences.Preferences | null = null
if (this.innerContext) {
await preferences.getPreferences(this.innerContext, consts.DATA_BASE_NAME).then((pref) => {
prefer = pref;
})
}
if (!prefer) {
return;
}
let records: Array<string> = [];
await (prefer as preferences.Preferences).get(consts.DATA_BASE_KEY_TOTAL_TIMES, [])
.then((value: preferences.ValueType) => {
records = value as Array<string>;
})
for (let item of records) {
await (prefer as preferences.Preferences).get(item, []).then((detail: preferences.ValueType) => {
if (JSON.stringify(detail) !== '[]') {
this.dataSource.push(detail as Array<string>);
}
}).catch((error: BusinessError) => {
Logger.info(TAG, `Failed to get value code is ${error.code}`);
})
}
}
private dataSource: Array<Array<string>> = [];
private innerContext: common.UIAbilityContext | null = null;
}
-
参考接口:@ohos.app.ability.common,@ohos.data.preferences
-
设置模块
-
本模块分为三个事件,分别为记录联网事件,记录灭屏事件,记录亮屏事件,进行锁屏事件、进行解锁屏幕事件,每一个事件都可进行一直,仅本次和从不的单项选择,使用到应用文上下文吗,CommonEvent.publish发布公共事件,getPreferences方法获取Preferences实例进行功能页面开发。
-
源码参考:[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 '@kit.ArkUI';
@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.ets]
/*
* 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 { commonEventManager } from '@kit.BasicServicesKit';
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 = commonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE;
static readonly DATA_BASE_KEY_SCREEN_OFF: string = commonEventManager.Support.COMMON_EVENT_SCREEN_OFF;
static readonly DATA_BASE_KEY_SCREEN_ON: string = commonEventManager.Support.COMMON_EVENT_SCREEN_ON;
static readonly DATA_BASE_KEY_SCREEN_LOCKED: string = commonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED;
static readonly DATA_BASE_KEY_SCREEN_UNLOCKED: string = commonEventManager.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";
}
- 源码参考:[SettingFeature.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 { commonEventManager, BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
import consts from '../module/Consts';
import { preferences } from '@kit.ArkData';
import Logger from '../module/Logger';
import surveillanceEventsManager from '../module/SurveillanceEventsManager';
import { GlobalContext } from '../module/GlobalContext';
export default class SettingFeature {
private innerContext: common.UIAbilityContext | null = null;
private pref: preferences.Preferences | null = null;
constructor(abilityContext: common.UIAbilityContext) {
this.innerContext = abilityContext;
}
async init() {
if (this.innerContext) {
await preferences.getPreferences(this.innerContext, consts.DATA_BASE_NAME).then((pref => {
this.pref = pref;
})).catch((err: BusinessError) => {
Logger.info(`getPreferences err ${JSON.stringify(err)}`);
})
}
}
changeState(group: string, state: number) {
GlobalContext.getContext().setObject(group, state);
let options: commonEventManager.CommonEventPublishData = {
isSticky: true,
parameters: surveillanceEventsManager.getSurveillanceEventStates()
}
commonEventManager.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 (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(group) == consts.ENABLE_STATE_ALWAYS;
}
checkStateForOnce(group: string): boolean {
return (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(group) == consts.ENABLE_STATE_ONCE;
}
checkStateForNever(group: string): boolean {
return (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).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.ets]
/*
* 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 { commonEventManager } from '@kit.BasicServicesKit';
import { GlobalContext } from './GlobalContext';
export default class SurveillanceEventsManager {
constructor() {
}
static getSurveillanceEventStates(): Record<string, number> {
return {
"usual.event.wifi.POWER_STATE": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE) as number,
"usual.event.SCREEN_OFF": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_SCREEN_OFF) as number,
"usual.event.SCREEN_ON": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_SCREEN_ON) as number,
"usual.event.SCREEN_LOCKED": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED) as number,
"usual.event.SCREEN_UNLOCKED": (GlobalContext.getContext()
.getObject('settings') as Map<string, number>).get(commonEventManager.Support.COMMON_EVENT_SCREEN_UNLOCKED) as number
}
}
static surveillanceEvents: Array<string> = [
commonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE,
commonEventManager.Support.COMMON_EVENT_SCREEN_OFF,
commonEventManager.Support.COMMON_EVENT_SCREEN_ON,
commonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED,
commonEventManager.Support.COMMON_EVENT_SCREEN_UNLOCKED,
]
}
-
参考接口:@ohos.app.ability.common,@ohos.data.preferences,@ohos.commonEvent, @ohos.router
-
关于模块
-
该模块开发主要介绍了本示例的功能作用以及说明了什么情况下不能使用。
-
源码参考:[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 '@kit.ArkUI';
@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.ets]
/*
* 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 { commonEventManager } from '@kit.BasicServicesKit';
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 = commonEventManager.Support.COMMON_EVENT_WIFI_POWER_STATE;
static readonly DATA_BASE_KEY_SCREEN_OFF: string = commonEventManager.Support.COMMON_EVENT_SCREEN_OFF;
static readonly DATA_BASE_KEY_SCREEN_ON: string = commonEventManager.Support.COMMON_EVENT_SCREEN_ON;
static readonly DATA_BASE_KEY_SCREEN_LOCKED: string = commonEventManager.Support.COMMON_EVENT_SCREEN_LOCKED;
static readonly DATA_BASE_KEY_SCREEN_UNLOCKED: string = commonEventManager.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";
}
以上就是本篇文章所带来的鸿蒙开发中一小部分技术讲解;想要学习完整的鸿蒙全栈技术。可以在结尾找我可全部拿到!
下面是鸿蒙的完整学习路线,展示如下:
除此之外,根据这个学习鸿蒙全栈学习路线,也附带一整套完整的学习【文档+视频】,内容包含如下:
内容包含了:(ArkTS、ArkUI、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、鸿蒙南向开发、鸿蒙项目实战)等技术知识点。帮助大家在学习鸿蒙路上快速成长!
鸿蒙【北向应用开发+南向系统层开发】文档
鸿蒙【基础+实战项目】视频
鸿蒙面经
为了避免大家在学习过程中产生更多的时间成本,对比我把以上内容全部放在了↓↓↓想要的可以自拿喔!谢谢大家观看!