未验证 提交 8500a78f 编写于 作者: O openharmony_ci 提交者: Gitee

!24003 feat: HiAppEvent示例代码ArkTs风格整改

Merge pull request !24003 from lyj/master
...@@ -47,53 +47,54 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制 ...@@ -47,53 +47,54 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制
1. 新建一个ArkTS应用工程,编辑工程中的“entry > src > main > ets > entryability > EntryAbility.ts” 文件,在onCreate函数中添加对用户点击按钮事件的订阅,完整示例代码如下: 1. 新建一个ArkTS应用工程,编辑工程中的“entry > src > main > ets > entryability > EntryAbility.ts” 文件,在onCreate函数中添加对用户点击按钮事件的订阅,完整示例代码如下:
```js ```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';
import hilog from '@ohos.hilog'; import hilog from '@ohos.hilog';
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window' import Want from '@ohos.app.ability.Want';
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent' import window from '@ohos.window';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? '');
hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? '');
hiAppEvent.addWatcher({ hiAppEvent.addWatcher({
// 开发者可以自定义观察者名称,系统会使用名称来标识不同的观察者 // 开发者可以自定义观察者名称,系统会使用名称来标识不同的观察者
name: "watcher1", name: "watcher1",
// 开发者可以订阅感兴趣的应用事件,此处是订阅了按钮事件 // 开发者可以订阅感兴趣的应用事件,此处是订阅了按钮事件
appEventFilters: [{ domain: "button" }], appEventFilters: [{ domain: "button" }],
// 开发者可以设置订阅回调触发的条件,此处是设置为事件打点数量满足1个 // 开发者可以设置订阅回调触发的条件,此处是设置为事件打点数量满足1个
triggerCondition: { row: 1 }, triggerCondition: { row: 1 },
// 开发者可以自行实现订阅回调函数,以便对订阅获取到的事件打点数据进行自定义处理 // 开发者可以自行实现订阅回调函数,以便对订阅获取到的事件打点数据进行自定义处理
onTrigger: function (curRow, curSize, holder) { onTrigger: (curRow: number, curSize: number, holder: hiAppEvent.AppEventPackageHolder) => {
// 返回的holder对象为null,表示订阅过程发生异常,因此在记录错误日志后直接返回 // 返回的holder对象为null,表示订阅过程发生异常,因此在记录错误日志后直接返回
if (holder == null) { if (holder == null) {
hilog.error(0x0000, 'testTag', "HiAppEvent holder is null") hilog.error(0x0000, 'testTag', "HiAppEvent holder is null");
return return;
} }
let eventPkg = null hilog.info(0x0000, 'testTag', `HiAppEvent onTrigger: curRow=%{public}d, curSize=%{public}d`, curRow, curSize);
// 根据设置阈值大小(默认为512KB)去获取订阅事件包,直到将订阅数据全部取出 let eventPkg: hiAppEvent.AppEventPackage | null = null;
// 返回的事件包对象为null,表示当前订阅数据已被全部取出,此次订阅回调触发结束 // 根据设置阈值大小(默认为512KB)去获取订阅事件包,直到将订阅数据全部取出
while ((eventPkg = holder.takeNext()) != null) { // 返回的事件包对象为null,表示当前订阅数据已被全部取出,此次订阅回调触发结束
// 开发者可以对事件包中的事件打点数据进行自定义处理,此处是将事件打点数据打印在日志中 while ((eventPkg = holder.takeNext()) != null) {
hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.packageId=%{public}d`, eventPkg.packageId) // 开发者可以对事件包中的事件打点数据进行自定义处理,此处是将事件打点数据打印在日志中
hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.row=%{public}d`, eventPkg.row) hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.packageId=%{public}d`, eventPkg.packageId);
hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.size=%{public}d`, eventPkg.size) hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.row=%{public}d`, eventPkg.row);
for (const eventInfo of eventPkg.data) { hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.size=%{public}d`, eventPkg.size);
hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.info=%{public}s`, eventInfo) for (const eventInfo of eventPkg.data) {
} hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.info=%{public}s`, eventInfo);
} }
} }
}) }
} });
}
} }
2. 编辑工程中的entry > src > main > ets > pages > Index.ets 文件添加一个按钮并在其onClick函数中进行事件打点以记录按钮点击事件完整示例代码如下 2. 编辑工程中的entry > src > main > ets > pages > Index.ets 文件添加一个按钮并在其onClick函数中进行事件打点以记录按钮点击事件完整示例代码如下
```js ```ts
import { BusinessError } from 'ohos.base'
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent' import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'
import hilog from '@ohos.hilog' import hilog from '@ohos.hilog'
...@@ -111,7 +112,8 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制 ...@@ -111,7 +112,8 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制
Button("writeTest").onClick(()=>{ Button("writeTest").onClick(()=>{
// 在按钮点击函数中进行事件打点,以记录按钮点击事件 // 在按钮点击函数中进行事件打点,以记录按钮点击事件
hiAppEvent.write({ let eventParams: Record<string, number> = { 'click_time': 100 };
let eventInfo: hiAppEvent.AppEventInfo = {
// 事件领域定义 // 事件领域定义
domain: "button", domain: "button",
// 事件名称定义 // 事件名称定义
...@@ -119,12 +121,13 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制 ...@@ -119,12 +121,13 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制
// 事件类型定义 // 事件类型定义
eventType: hiAppEvent.EventType.BEHAVIOR, eventType: hiAppEvent.EventType.BEHAVIOR,
// 事件参数定义 // 事件参数定义
params: { click_time: 100 } params: eventParams,
}).then(() => { };
hiAppEvent.write(eventInfo).then(() => {
hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`) hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`)
}).catch((err) => { }).catch((err: BusinessError) => {
hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`) hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`)
}) });
}) })
} }
.width('100%') .width('100%')
...@@ -137,15 +140,11 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制 ...@@ -137,15 +140,11 @@ HiAppEvent是在系统层面为应用开发者提供的一种事件打点机制
3. 点击IDE界面中的运行按钮,运行应用工程,然后在应用界面中点击按钮“writeTest”,触发一次按钮点击事件打点。 3. 点击IDE界面中的运行按钮,运行应用工程,然后在应用界面中点击按钮“writeTest”,触发一次按钮点击事件打点。
4. 最终,可以在Log窗口看到按钮点击事件打点成功的日志,以及触发订阅回调后对打点事件数据的处理日志: 4. 最终,可以在Log窗口看到按钮点击事件打点成功的日志,以及触发订阅回调后对打点事件数据的处理日志:
> HiAppEvent success to write event
```js > HiAppEvent eventPkg.packageId=0
HiAppEvent success to write event > HiAppEvent eventPkg.row=1
> HiAppEvent eventPkg.size=124
HiAppEvent eventPkg.packageId=0 > HiAppEvent eventPkg.info={"domain\_":"button","name\_":"click","type\_":4,"time\_":1670268234523,"tz\_":"+0800","pid\_":3295,"tid\_":3309,"click_time":100}
HiAppEvent eventPkg.row=1
HiAppEvent eventPkg.size=124
HiAppEvent eventPkg.info={"domain_":"button","name_":"click","type_":4,"time_":1670268234523,"tz_":"+0800","pid_":3295,"tid_":3309,"click_time":100}
```
## 相关实例 ## 相关实例
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
## 导入模块 ## 导入模块
```js ```ts
import hiAppEvent from '@ohos.hiAppEvent'; import hiAppEvent from '@ohos.hiAppEvent';
``` ```
...@@ -64,16 +64,21 @@ write(eventName: string, eventType: EventType, keyValues: object, callback: Asyn ...@@ -64,16 +64,21 @@ write(eventName: string, eventType: EventType, keyValues: object, callback: Asyn
**示例:** **示例:**
```js ```ts
hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}, (err, value) => { import { BusinessError } from 'ohos.base'
if (err) {
// 事件写入异常:事件存在异常参数时忽略异常参数后继续写入,或者事件校验失败时不执行写入 let eventParams: Record<string, number | string> = {
console.error(`failed to write event because ${err.code}`); "int_data": 100,
return; "str_data": "strValue",
} };
hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, eventParams, (err: BusinessError) => {
// 事件写入正常 if (err) {
console.log(`success to write event: ${value}`); // 事件写入异常:事件存在异常参数时忽略异常参数后继续写入,或者事件校验失败时不执行写入
console.error(`failed to write event, code=${err.code}`);
return;
}
// 事件写入正常
console.log(`success to write event`);
}); });
``` ```
...@@ -102,15 +107,20 @@ write(eventName: string, eventType: EventType, keyValues: object): Promise&lt;vo ...@@ -102,15 +107,20 @@ write(eventName: string, eventType: EventType, keyValues: object): Promise&lt;vo
**示例:** **示例:**
```js ```ts
hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}) import { BusinessError } from 'ohos.base'
.then((value) => {
// 事件写入正常 let eventParams: Record<string, number | string> = {
console.log(`success to write event: ${value}`); "int_data": 100,
}).catch((err) => { "str_data": "strValue",
// 事件写入异常:事件存在异常参数时忽略异常参数后继续写入,或者事件校验失败时不执行写入 };
console.error(`failed to write event because ${err.code}`); hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, eventParams).then(() => {
}); // 事件写入正常
console.log(`success to write event`);
}).catch((err: BusinessError) => {
// 事件写入异常:事件存在异常参数时忽略异常参数后继续写入,或者事件校验失败时不执行写入
console.error(`failed to write event, code=${err.code}`);
});
``` ```
## hiAppEvent.configure ## hiAppEvent.configure
...@@ -135,16 +145,18 @@ configure(config: ConfigOption): boolean ...@@ -135,16 +145,18 @@ configure(config: ConfigOption): boolean
**示例:** **示例:**
```js ```ts
// 配置应用事件打点功能开关 // 配置应用事件打点功能开关
hiAppEvent.configure({ let config1: hiAppEvent.ConfigOption = {
disable: true disable: true,
}); };
hiAppEvent.configure(config1);
// 配置事件文件目录存储限额大小 // 配置事件文件目录存储限额大小
hiAppEvent.configure({ let config2: hiAppEvent.ConfigOption = {
maxStorage: '100M' maxStorage: '100M',
}); };
hiAppEvent.configure(config2);
``` ```
## ConfigOption ## ConfigOption
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
## 导入模块 ## 导入模块
```js ```ts
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'; import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';
``` ```
...@@ -44,21 +44,24 @@ write(info: [AppEventInfo](#appeventinfo), callback: AsyncCallback&lt;void&gt;): ...@@ -44,21 +44,24 @@ write(info: [AppEventInfo](#appeventinfo), callback: AsyncCallback&lt;void&gt;):
**示例:** **示例:**
```js ```ts
import { BusinessError } from 'ohos.base';
let eventParams: Record<string, number | string> = {
"int_data": 100,
"str_data": "strValue",
};
hiAppEvent.write({ hiAppEvent.write({
domain: "test_domain", domain: "test_domain",
name: "test_event", name: "test_event",
eventType: hiAppEvent.EventType.FAULT, eventType: hiAppEvent.EventType.FAULT,
params: { params: eventParams,
int_data: 100, }, (err: BusinessError) => {
str_data: "strValue" if (err) {
} console.error(`code: ${err.code}, message: ${err.message}`);
}, (err) => { return;
if (err) { }
console.error(`code: ${err.code}, message: ${err.message}`); console.log(`success to write event`);
return;
}
console.log(`success to write event`);
}); });
``` ```
...@@ -98,19 +101,22 @@ write(info: [AppEventInfo](#appeventinfo)): Promise&lt;void&gt; ...@@ -98,19 +101,22 @@ write(info: [AppEventInfo](#appeventinfo)): Promise&lt;void&gt;
**示例:** **示例:**
```js ```ts
import { BusinessError } from 'ohos.base';
let eventParams: Record<string, number | string> = {
"int_data": 100,
"str_data": "strValue",
};
hiAppEvent.write({ hiAppEvent.write({
domain: "test_domain", domain: "test_domain",
name: "test_event", name: "test_event",
eventType: hiAppEvent.EventType.FAULT, eventType: hiAppEvent.EventType.FAULT,
params: { params: eventParams,
int_data: 100,
str_data: "strValue"
}
}).then(() => { }).then(() => {
console.log(`success to write event`); console.log(`success to write event`);
}).catch((err) => { }).catch((err: BusinessError) => {
console.error(`code: ${err.code}, message: ${err.message}`); console.error(`code: ${err.code}, message: ${err.message}`);
}); });
``` ```
...@@ -151,16 +157,18 @@ configure(config: [ConfigOption](configoption)): void ...@@ -151,16 +157,18 @@ configure(config: [ConfigOption](configoption)): void
**示例:** **示例:**
```js ```ts
// 配置打点开关为关闭状态 // 配置打点开关为关闭状态
hiAppEvent.configure({ let config1: hiAppEvent.ConfigOption = {
disable: true disable: true,
}); };
hiAppEvent.configure(config1);
// 配置文件目录存储配额为100M // 配置文件目录存储配额为100M
hiAppEvent.configure({ let config2: hiAppEvent.ConfigOption = {
maxStorage: '100M' maxStorage: '100M',
}); };
hiAppEvent.configure(config2);
``` ```
## ConfigOption ## ConfigOption
...@@ -208,52 +216,53 @@ addWatcher(watcher: [Watcher](#watcher)): [AppEventPackageHolder](#appeventpacka ...@@ -208,52 +216,53 @@ addWatcher(watcher: [Watcher](#watcher)): [AppEventPackageHolder](#appeventpacka
**示例:** **示例:**
```js ```ts
// 1. 如果观察者传入了回调的相关参数,则可以选择在自动触发的回调函数中对订阅事件进行处理 // 1. 如果观察者传入了回调的相关参数,则可以选择在自动触发的回调函数中对订阅事件进行处理
hiAppEvent.addWatcher({ hiAppEvent.addWatcher({
name: "watcher1", name: "watcher1",
appEventFilters: [ appEventFilters: [
{ {
domain: "test_domain", domain: "test_domain",
eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR] eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR]
} }
], ],
triggerCondition: { triggerCondition: {
row: 10, row: 10,
size: 1000, size: 1000,
timeOut: 1 timeOut: 1
}, },
onTrigger: function (curRow, curSize, holder) { onTrigger: (curRow: number, curSize: number, holder: hiAppEvent.AppEventPackageHolder) => {
if (holder == null) { if (holder == null) {
console.error("holder is null"); console.error("holder is null");
return; return;
}
let eventPkg = null;
while ((eventPkg = holder.takeNext()) != null) {
console.info(`eventPkg.packageId=${eventPkg.packageId}`);
console.info(`eventPkg.row=${eventPkg.row}`);
console.info(`eventPkg.size=${eventPkg.size}`);
for (const eventInfo of eventPkg.data) {
console.info(`eventPkg.data=${eventInfo}`);
}
}
} }
console.info(`curRow=${curRow}, curSize=${curSize}`);
let eventPkg: hiAppEvent.AppEventPackage | null = null;
while ((eventPkg = holder.takeNext()) != null) {
console.info(`eventPkg.packageId=${eventPkg.packageId}`);
console.info(`eventPkg.row=${eventPkg.row}`);
console.info(`eventPkg.size=${eventPkg.size}`);
for (const eventInfo of eventPkg.data) {
console.info(`eventPkg.data=${eventInfo}`);
}
}
}
}); });
// 2. 如果观察者未传入回调的相关参数,则可以选择使用返回的holder对象手动去处理订阅事件 // 2. 如果观察者未传入回调的相关参数,则可以选择使用返回的holder对象手动去处理订阅事件
let holder = hiAppEvent.addWatcher({ let holder = hiAppEvent.addWatcher({
name: "watcher2", name: "watcher2",
}); });
if (holder != null) { if (holder != null) {
let eventPkg = null; let eventPkg: hiAppEvent.AppEventPackage | null = null;
while ((eventPkg = holder.takeNext()) != null) { while ((eventPkg = holder.takeNext()) != null) {
console.info(`eventPkg.packageId=${eventPkg.packageId}`); console.info(`eventPkg.packageId=${eventPkg.packageId}`);
console.info(`eventPkg.row=${eventPkg.row}`); console.info(`eventPkg.row=${eventPkg.row}`);
console.info(`eventPkg.size=${eventPkg.size}`); console.info(`eventPkg.size=${eventPkg.size}`);
for (const eventInfo of eventPkg.data) { for (const eventInfo of eventPkg.data) {
console.info(`eventPkg.data=${eventInfo}`); console.info(`eventPkg.data=${eventInfo}`);
}
} }
}
} }
``` ```
...@@ -281,10 +290,10 @@ removeWatcher(watcher: [Watcher](#watcher)): void ...@@ -281,10 +290,10 @@ removeWatcher(watcher: [Watcher](#watcher)): void
**示例:** **示例:**
```js ```ts
// 1. 定义一个应用事件观察者 // 1. 定义一个应用事件观察者
let watcher = { let watcher: hiAppEvent.Watcher = {
name: "watcher1", name: "watcher1",
} }
// 2. 添加一个应用事件观察者来订阅事件 // 2. 添加一个应用事件观察者来订阅事件
...@@ -352,9 +361,9 @@ constructor(watcherName: string) ...@@ -352,9 +361,9 @@ constructor(watcherName: string)
**示例:** **示例:**
```js ```ts
let holder = hiAppEvent.addWatcher({ let holder1 = hiAppEvent.addWatcher({
name: "watcher", name: "watcher1",
}); });
``` ```
...@@ -382,11 +391,11 @@ setSize(size: number): void ...@@ -382,11 +391,11 @@ setSize(size: number): void
**示例:** **示例:**
```js ```ts
let holder = hiAppEvent.addWatcher({ let holder2 = hiAppEvent.addWatcher({
name: "watcher", name: "watcher2",
}); });
holder.setSize(1000); holder2.setSize(1000);
``` ```
### takeNext ### takeNext
...@@ -399,11 +408,11 @@ takeNext(): [AppEventPackage](#appeventpackage) ...@@ -399,11 +408,11 @@ takeNext(): [AppEventPackage](#appeventpackage)
**示例:** **示例:**
```js ```ts
let holder = hiAppEvent.addWatcher({ let holder3 = hiAppEvent.addWatcher({
name: "watcher", name: "watcher3",
}); });
let eventPkg = holder.takeNext(); let eventPkg = holder3.takeNext();
``` ```
## AppEventPackage ## AppEventPackage
...@@ -429,7 +438,7 @@ clearData(): void ...@@ -429,7 +438,7 @@ clearData(): void
**示例:** **示例:**
```js ```ts
hiAppEvent.clearData(); hiAppEvent.clearData();
``` ```
......
...@@ -22,7 +22,9 @@ Function is disabled. ...@@ -22,7 +22,9 @@ Function is disabled.
调用配置接口开启打点功能。 调用配置接口开启打点功能。
```js ```ts
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';
hiAppEvent.configure({ hiAppEvent.configure({
disable: false disable: false
}); });
...@@ -185,7 +187,7 @@ Invalid filtering event domain. ...@@ -185,7 +187,7 @@ Invalid filtering event domain.
- 事件领域名称只包含数字、小写字母、下划线字符。 - 事件领域名称只包含数字、小写字母、下划线字符。
- 事件领域名称以小写字母开头,不以下划线结尾。 - 事件领域名称以小写字母开头,不以下划线结尾。
- 事件领域名称非空且长度不超过32个字符。 - 事件领域名称非空且长度不超过16个字符。
**处理步骤** **处理步骤**
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册