1# 事件订阅(C/C++) 2 3<!--Kit: Performance Analysis Kit--> 4<!--Subsystem: HiviewDFX--> 5<!--Owner: @liujiaxing2024--> 6<!--Designer: @junjie_shi--> 7<!--Tester: @gcw_KuLfPSbe--> 8<!--Adviser: @foryourself--> 9 10HiAppEvent提供了事件订阅接口,用于获取应用的事件。 11 12## 接口说明 13 14API接口的使用说明,包括参数使用限制和取值范围,请参考[HiAppEvent C API文档](../reference/apis-performance-analysis-kit/capi-hiappevent-h.md)。 15 16**订阅接口功能介绍**: 17 18| 接口名 | 描述 | 19| -------- | -------- | 20| int OH_HiAppEvent_AddWatcher(HiAppEvent_Watcher* watcher) | 添加应用的事件观察者。 | 21| int OH_HiAppEvent_RemoveWatcher(HiAppEvent_Watcher* watcher) | 移除应用的事件观察者。 | 22 23**打点接口功能介绍**: 24 25| 接口名 | 描述 | 26| -------- | -------- | 27| int OH_HiAppEvent_Write(const char* domain, const char* name, enum EventType type, const ParamList list) | 实现对参数为列表类型的应用事件打点。 | 28 29## 事件订阅开发指导 30 31以订阅崩溃事件(系统事件)和按钮点击事件(应用事件)为例,说明开发步骤。 32 33### 步骤一:新建工程及编译配置 34 351. 获取该示例工程依赖的jsoncpp文件, 36 从[三方开源库jsoncpp代码仓](https://github.com/open-source-parsers/jsoncpp)下载源码的压缩包,并按照README的**Amalgamated source**中介绍的操作步骤得到jsoncpp.cpp、json.h和json-forwards.h三个文件。 37 新建Native C++工程,并将jsoncpp导入工程,目录结构如下: 38 39 ```text 40 entry 41 └── src 42 └── main 43 ├── cpp 44 │ ├── CMakeLists.txt 45 │ ├── json 46 │ │ ├── json-forwards.h 47 │ │ └── json.h 48 │ ├── jsoncpp.cpp 49 │ ├── napi_init.cpp 50 │ └── types 51 │ └── libentry 52 │ ├── Index.d.ts 53 │ └── oh-package.json5 54 └── ets 55 ├── entryability 56 │ └── EntryAbility.ets 57 └── pages 58 └── Index.ets 59 ``` 60 612. 编辑“CMakeLists.txt”文件,添加源文件和动态库。 62 63 ```cmake 64 # 新增jsoncpp.cpp(解析订阅事件中的json字符串)源文件 65 add_library(entry SHARED napi_init.cpp jsoncpp.cpp) 66 # 新增动态库依赖libhiappevent_ndk.z.so和libhilog_ndk.z.so(日志输出) 67 target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libhiappevent_ndk.z.so) 68 ``` 69 703. 编辑“napi_init.cpp”文件,导入依赖的文件并定义LOG_TAG: 71 72 ```c++ 73 #include "napi/native_api.h" 74 #include "json/json.h" 75 #include "hilog/log.h" 76 #include "hiappevent/hiappevent.h" 77 78 #undef LOG_TAG 79 #define LOG_TAG "testTag" 80 ``` 81 82### 步骤二:订阅事件 83 841. 订阅事件。分别使用OnReceive类型观察者、OnTrigger类型观察者的订阅方式。 85 - 订阅崩溃事件(系统事件),采用OnReceive类型观察者的订阅方式,观察者接收到事件后会立即触发OnReceive()回调。编辑“napi_init.cpp”文件,定义OnReceive类型观察者相关方法: 86 87 ```c++ 88 // 定义变量,用来缓存创建的观察者的指针。 89 static HiAppEvent_Watcher *onReceiverWatcher; 90 91 static void OnReceive(const char *domain, const struct HiAppEvent_AppEventGroup *appEventGroups, uint32_t groupLen) { 92 for (int i = 0; i < groupLen; ++i) { 93 for (int j = 0; j < appEventGroups[i].infoLen; ++j) { 94 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", appEventGroups[i].appEventInfos[j].domain); 95 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", appEventGroups[i].appEventInfos[j].name); 96 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", appEventGroups[i].appEventInfos[j].type); 97 if (strcmp(appEventGroups[i].appEventInfos[j].domain, DOMAIN_OS) == 0 && 98 strcmp(appEventGroups[i].appEventInfos[j].name, EVENT_APP_CRASH) == 0) { 99 Json::Value params; 100 Json::Reader reader(Json::Features::strictMode()); 101 Json::FastWriter writer; 102 if (reader.parse(appEventGroups[i].appEventInfos[j].params, params)) { 103 // 开发者可以获取到崩溃事件发生的时间戳 104 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", params["time"].asInt64()); 105 // 开发者可以获取到崩溃应用的包名 106 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_name=%{public}s", params["bundle_name"].asString().c_str()); 107 auto external_log = writer.write(params["external_log"]); 108 // 开发者可以获取到崩溃事件发生时的故障日志文件 109 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", external_log.c_str()); 110 } 111 } 112 } 113 } 114 } 115 static napi_value RegisterWatcherCrash(napi_env env, napi_callback_info info) { 116 // 开发者自定义观察者名称,系统根据不同的名称来识别不同的观察者。 117 onReceiverWatcher = OH_HiAppEvent_CreateWatcher("AppCrashWatcher"); 118 // 设置订阅的事件名称为EVENT_APP_CRASH,即崩溃事件。 119 const char *names[] = {EVENT_APP_CRASH}; 120 // 开发者订阅感兴趣的事件,此处订阅了系统事件。 121 OH_HiAppEvent_SetAppEventFilter(onReceiverWatcher, DOMAIN_OS, 0, names, 1); 122 // 开发者设置已实现的回调函数,观察者接收到事件后回立即触发OnReceive回调。 123 OH_HiAppEvent_SetWatcherOnReceive(onReceiverWatcher, OnReceive); 124 // 使观察者开始监听订阅的事件。 125 OH_HiAppEvent_AddWatcher(onReceiverWatcher); 126 return {}; 127 } 128 ``` 129 130 - 订阅按钮点击事件(应用事件),采用OnTrigger类型观察者的订阅方式。需满足OH_HiAppEvent_SetTriggerCondition()设置的条件,才能触发OnTrigger()回调。编辑 “napi_init.cpp”文件,定义OnTrigger类型观察者相关方法: 131 132 ```c++ 133 // 定义变量,用来缓存创建的观察者的指针。 134 static HiAppEvent_Watcher *onTriggerWatcher; 135 // 开发者可以自行实现获取已监听到事件的回调函数,其中events指针指向内容仅在该函数内有效。 136 static void OnTake(const char *const *events, uint32_t eventLen) { 137 Json::Reader reader(Json::Features::strictMode()); 138 for (int i = 0; i < eventLen; ++i) { 139 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo=%{public}s", events[i]); 140 Json::Value eventInfo; 141 if (reader.parse(events[i], eventInfo)) { 142 auto domain = eventInfo["domain_"].asString(); 143 auto name = eventInfo["name_"].asString(); 144 auto type = eventInfo["type_"].asInt(); 145 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", domain.c_str()); 146 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", name.c_str()); 147 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", type); 148 if (domain == "button" && name == "click") { 149 auto clickTime = eventInfo["click_time"].asInt64(); 150 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.click_time=%{public}lld", clickTime); 151 } 152 } 153 } 154 } 155 156 // 开发者可以自行实现订阅回调函数,以便对获取到的事件打点数据进行自定义处理。 157 static void OnTrigger(int row, int size) { 158 // 接收回调后,获取指定数量的已接收事件。 159 OH_HiAppEvent_TakeWatcherData(onTriggerWatcher, row, OnTake); 160 } 161 162 static napi_value RegisterWatcherClick(napi_env env, napi_callback_info info) { 163 // 开发者自定义观察者名称,系统根据不同的名称来识别不同的观察者。 164 onTriggerWatcher = OH_HiAppEvent_CreateWatcher("ButtonClickWatcher"); 165 // 设置订阅的事件名称为click。 166 const char *names[] = {"click"}; 167 // 开发者订阅感兴趣的应用事件,此处订阅了button相关事件。 168 OH_HiAppEvent_SetAppEventFilter(onTriggerWatcher, "button", 0, names, 1); 169 // 开发者设置已实现的回调函数,需OH_HiAppEvent_SetTriggerCondition设置的条件满足方可触发。 170 OH_HiAppEvent_SetWatcherOnTrigger(onTriggerWatcher, OnTrigger); 171 // 开发者可以设置订阅触发回调的条件,此处是设置新增事件打点数量为1个时,触发onTrigger回调。 172 OH_HiAppEvent_SetTriggerCondition(onTriggerWatcher, 1, 0, 0); 173 // 使观察者开始监听订阅的事件。 174 OH_HiAppEvent_AddWatcher(onTriggerWatcher); 175 return {}; 176 } 177 ``` 178 1792. 编辑“napi_init.cpp”文件,添加按钮点击事件的打点接口: 180 181 ```c++ 182 static napi_value WriteAppEvent(napi_env env, napi_callback_info info) { 183 auto params = OH_HiAppEvent_CreateParamList(); 184 OH_HiAppEvent_AddInt64Param(params, "click_time", time(nullptr)); 185 OH_HiAppEvent_Write("button", "click", EventType::BEHAVIOR, params); 186 OH_HiAppEvent_DestroyParamList(params); 187 return {}; 188 } 189 ``` 190 1913. 编辑“napi_init.cpp”文件,注册RegisterWatcherCrash()(订阅崩溃事件)、RegisterWatcherClick()(订阅按钮点击事件)、WriteAppEvent()(按钮点击事件打点接口)为ArkTS接口: 192 193 ```c++ 194 static napi_value Init(napi_env env, napi_value exports) 195 { 196 napi_property_descriptor desc[] = { 197 { "registerWatcherCrash", nullptr, RegisterWatcherCrash, nullptr, nullptr, nullptr, napi_default, nullptr }, 198 { "registerWatcherClick", nullptr, RegisterWatcherClick, nullptr, nullptr, nullptr, napi_default, nullptr }, 199 { "writeAppEvent", nullptr, WriteAppEvent, nullptr, nullptr, nullptr, napi_default, nullptr } 200 }; 201 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 202 return exports; 203 } 204 ``` 205 2064. 编辑“index.d.ts”文件,定义ArkTS接口: 207 208 ```ts 209 export const registerWatcherCrash: () => void; 210 export const registerWatcherClick: () => void; 211 export const writeAppEvent: () => void; 212 ``` 213 2145. 编辑“EntryAbility.ets”文件,在onCreate()函数中添加接口调用: 215 216 ```ts 217 // 导入依赖模块 218 import testNapi from 'libentry.so'; 219 220 // 在onCreate()函数中添加接口调用 221 // 启动时,注册崩溃事件观察者 222 testNapi.registerWatcherCrash(); 223 // 启动时,注册按钮点击事件观察者 224 testNapi.registerWatcherClick(); 225 ``` 226 227### 步骤三:触发事件 228 229编辑“Index.ets”文件,新增“appCrash”按钮以触发崩溃事件;新增“buttonClick”按钮,在按钮点击函数中进行事件打点。示例代码如下: 230 231```ts 232// 导入依赖模块 233import testNapi from 'libentry.so'; 234 235@Entry 236@Component 237struct Index { 238 build() { 239 Row() { 240 Column() { 241 Button("appCrash") 242 .onClick(() => { 243 // 在按钮点击函数中构造一个crash场景,触发应用崩溃事件 244 let result: object = JSON.parse(""); 245 }) 246 .position({ x: 100, y: 100 }) // 设置按钮位置 247 248 Button("buttonClick") 249 .onClick(() => { 250 // 在按钮点击函数中进行事件打点,以记录按钮点击事件 251 testNapi.writeAppEvent(); 252 }) 253 .position({ x: 100, y: 200 }) // 设置按钮位置 254 } 255 .width('100%') 256 } 257 .height('100%') 258 } 259} 260``` 261 262## 调测验证 263 2641. 点击DevEco Studio界面中的运行按钮,运行应用工程。在应用界面中点击“appCrash”按钮,触发崩溃事件。应用退出后重新打开应用。 265 2662. 搜索关键字“HiAppEvent”,在HiLog窗口查看应用处理崩溃事件数据的日志: 267 268 ```text 269 HiAppEvent eventInfo.domain=OS 270 HiAppEvent eventInfo.name=APP_CRASH 271 HiAppEvent eventInfo.eventType=1 272 HiAppEvent eventInfo.params.time=1750946685473 273 HiAppEvent eventInfo.params.bundle_name=com.example.cxxxx 274 HiAppEvent eventInfo.params.external_log=["/data/storage/el2/log/hiappevent/APP_CRASH_1750946685805_64003.log"] 275 ``` 276 2773. 点击buttonClick按钮,触发按钮点击事件。搜索关键字“HiAppEvent”,在HiLog窗口查看应用处理按钮点击事件数据的日志: 278 279 ```text 280 HiAppEvent eventInfo={"domain_":"button","name_":"click","type_":4,"time_":1750947007108,"tz_":"","pid_":64750,"tid_":64750,"click_time":1750947007} 281 HiAppEvent eventInfo.domain=button 282 HiAppEvent eventInfo.name=click 283 HiAppEvent eventInfo.eventType=4 284 HiAppEvent eventInfo.params.click_time=1750947007 285 ``` 286 2874. 移除应用的事件观察者: 288 289 ```c++ 290 static napi_value RemoveWatcher(napi_env env, napi_callback_info info) { 291 // 使观察者停止监听事件 292 OH_HiAppEvent_RemoveWatcher(appEventWatcher); 293 return {}; 294 } 295 ``` 296 2975. 销毁应用的事件观察者: 298 299 ```c++ 300 static napi_value DestroyWatcher(napi_env env, napi_callback_info info) { 301 // 销毁创建的观察者,并置appEventWatcher为nullptr 302 OH_HiAppEvent_DestroyWatcher(appEventWatcher); 303 appEventWatcher = nullptr; 304 return {}; 305 } 306 ``` 307