1# 订阅卡死事件(C/C++)
2
3## 接口说明
4
5API接口的具体使用说明(参数使用限制、具体取值范围等)请参考[HiAppEvent](../reference/apis-performance-analysis-kit/_hi_app_event.md#hiappevent)。
6
7**订阅接口功能介绍:**
8
9| 接口名                                                       | 描述                                         |
10| ------------------------------------------------------------ | -------------------------------------------- |
11| int OH_HiAppEvent_AddWatcher (HiAppEvent_Watcher \*watcher)  | 添加应用事件观察者,以添加对应用事件的订阅。 |
12| int OH_HiAppEvent_RemoveWatcher (HiAppEvent_Watcher *watcher) | 移除应用事件观察者,以移除对应用事件的订阅。 |
13
14## 开发步骤
15
16以实现对用户点击按钮触发卡顿场景生成的卡顿事件订阅为例,说明开发步骤。
17
181. 新建Native C++工程,并将jsoncpp导入到新建工程内,目录结构如下:
19
20   ```yml
21   entry:
22     src:
23       main:
24         cpp:
25           - json:
26               - json.h
27               - json-forwards.h
28           - types:
29               libentry:
30                 - index.d.ts
31           - CMakeLists.txt
32           - napi_init.cpp
33           - jsoncpp.cpp
34         ets:
35           - entryability:
36               - EntryAbility.ets
37           - pages:
38               - Index.ets
39   ```
40
412. 编辑"CMakeLists.txt"文件,添加源文件及动态库:
42
43   ```cmake
44   # 新增jsoncpp.cpp(解析订阅事件中的json字符串)源文件
45   add_library(entry SHARED napi_init.cpp jsoncpp.cpp)
46   # 新增动态库依赖libhiappevent_ndk.z.solibhilog_ndk.z.so(日志输出)
47   target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libhiappevent_ndk.z.so)
48   ```
49
503. 编辑"napi_init.cpp"文件,导入依赖的文件,并定义LOG_TAG:
51
52   ```c++
53   #include "napi/native_api.h"
54   #include "json/json.h"
55   #include "hilog/log.h"
56   #include "hiappevent/hiappevent.h"
57
58   #undef LOG_TAG
59   #define LOG_TAG "testTag"
60   ```
61
624. 订阅系统事件:
63
64   - onReceive类型观察者:
65
66     编辑"napi_init.cpp"文件,定义onReceive类型观察者相关方法:
67
68     ```c++
69     //定义一变量,用来缓存创建的观察者的指针。
70     static HiAppEvent_Watcher *systemEventWatcher;
71
72     static void OnReceive(const char *domain, const struct HiAppEvent_AppEventGroup *appEventGroups, uint32_t groupLen) {
73         for (int i = 0; i < groupLen; ++i) {
74             for (int j = 0; j < appEventGroups[i].infoLen; ++j) {
75                 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", appEventGroups[i].appEventInfos[j].domain);
76                 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", appEventGroups[i].appEventInfos[j].name);
77                 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", appEventGroups[i].appEventInfos[j].type);
78                 if (strcmp(appEventGroups[i].appEventInfos[j].domain, DOMAIN_OS) == 0 &&
79                     strcmp(appEventGroups[i].appEventInfos[j].name, EVENT_APP_FREEZE) == 0) {
80                     Json::Value params;
81                     Json::Reader reader(Json::Features::strictMode());
82                     Json::FastWriter writer;
83                     if (reader.parse(appEventGroups[i].appEventInfos[j].params, params)) {
84                         auto time = params["time"].asInt64();
85                         auto foreground = params["foreground"].asBool();
86                         auto bundleVersion = params["bundle_version"].asString();
87                         auto bundleName = params["bundle_name"].asString();
88                         auto processName = params["process_name"].asString();
89                         auto pid = params["pid"].asInt();
90                         auto uid = params["uid"].asInt();
91                         auto uuid = params["uuid"].asString();
92                         auto exception = writer.write(params["exception"]);
93                         auto hilogSize = params["hilog"].size();
94                         auto handleSize =  params["event_handler"].size();
95                         auto handleSize3s =  params["event_handler_size_3s"].asString();
96                         auto handleSize6s =  params["event_handler_size_6s"].asString();
97                         auto peerBindSize =  params["peer_binder"].size();
98                         auto threadSize =  params["threads"].size();
99                         auto memory =  writer.write(params["memory"]);
100                         auto externalLog = writer.write(params["external_log"]);
101                         auto logOverLimit = params["log_over_limit"].asBool();
102                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time);
103                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.foreground=%{public}d", foreground);
104                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str());
105                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_name=%{public}s", bundleName.c_str());
106                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str());
107                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid);
108                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid);
109                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str());
110                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str());
111                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize);
112                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler.size=%{public}d", handleSize);
113                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler_3s.size=%{public}s", handleSize3s.c_str());
114                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler_6s.size=%{public}s", handleSize6s.c_str());
115                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize);
116                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.threads.size=%{public}d", threadSize);
117                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str());
118                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str());
119                         OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit);
120                     }
121                 }
122             }
123         }
124     }
125
126     static napi_value RegisterWatcher(napi_env env, napi_callback_info info) {
127         // 开发者自定义观察者名称,系统根据不同的名称来识别不同的观察者。
128         systemEventWatcher = OH_HiAppEvent_CreateWatcher("onReceiverWatcher");
129         // 设置订阅的事件为EVENT_APP_FREEZE。
130         const char *names[] = {EVENT_APP_FREEZE};
131         // 开发者订阅感兴趣的事件,此处订阅了系统事件。
132         OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1);
133         // 开发者设置已实现的回调函数,观察者接收到事件后回立即触发OnReceive回调。
134         OH_HiAppEvent_SetWatcherOnReceive(systemEventWatcher, OnReceive);
135         // 使观察者开始监听订阅的事件。
136         OH_HiAppEvent_AddWatcher(systemEventWatcher);
137         return {};
138     }
139     ```
140
141   - onTrigger类型观察者:
142
143     编辑"napi_init.cpp"文件,定义OnTrigger类型观察者相关方法:
144
145     ```c++
146     //定义一变量,用来缓存创建的观察者的指针。
147     static HiAppEvent_Watcher *systemEventWatcher;
148
149     // 开发者可以自行实现获取已监听到事件的回调函数,其中events指针指向内容仅在该函数内有效。
150     static void OnTake(const char *const *events, uint32_t eventLen) {
151         Json::Reader reader(Json::Features::strictMode());
152         Json::FastWriter writer;
153         for (int i = 0; i < eventLen; ++i) {
154             Json::Value eventInfo;
155             if (reader.parse(events[i], eventInfo)) {
156                 auto domain =  eventInfo["domain_"].asString();
157                 auto name = eventInfo["name_"].asString();
158                 auto type = eventInfo["type_"].asInt();
159                 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", domain.c_str());
160                 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", name.c_str());
161                 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", type);
162                 if (domain ==  DOMAIN_OS && name == EVENT_APP_FREEZE) {
163                     auto time = eventInfo["time"].asInt64();
164                     auto foreground = eventInfo["foreground"].asBool();
165                     auto bundleVersion = eventInfo["bundle_version"].asString();
166                     auto bundleName = eventInfo["bundle_name"].asString();
167                     auto processName = eventInfo["process_name"].asString();
168                     auto pid = eventInfo["pid"].asInt();
169                     auto uid = eventInfo["uid"].asInt();
170                     auto uuid = eventInfo["uuid"].asString();
171                     auto exception = writer.write(eventInfo["exception"]);
172                     auto hilogSize = eventInfo["hilog"].size();
173                     auto handleSize =  eventInfo["event_handler"].size();
174                     auto handleSize3s =  eventInfo["event_handler_size_3s"].asString();
175                     auto handleSize6s =  eventInfo["event_handler_size_6s"].asString();
176                     auto peerBindSize =  eventInfo["peer_binder"].size();
177                     auto threadSize =  eventInfo["threads"].size();
178                      auto memory =  writer.write(eventInfo["memory"]);
179                     auto externalLog = writer.write(eventInfo["external_log"]);
180                     auto logOverLimit = eventInfo["log_over_limit"].asBool();
181                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time);
182                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.foreground=%{public}d", foreground);
183                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str());
184                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_name=%{public}s", bundleName.c_str());
185                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str());
186                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid);
187                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid);
188                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str());
189                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str());
190                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize);
191                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler.size=%{public}d", handleSize);
192                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler_3s.size=%{public}s", handleSize3s.c_str());
193                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler_6s.size=%{public}s", handleSize6s.c_str());
194                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize);
195                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.threads.size=%{public}d", threadSize);
196                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str());
197                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str());
198                     OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit);
199                 }
200             }
201         }
202     }
203
204     // 开发者可以自行实现订阅回调函数,以便对获取到的事件打点数据进行自定义处理。
205     static void OnTrigger(int row, int size) {
206         // 接收回调后,获取指定数量的已接收事件。
207         OH_HiAppEvent_TakeWatcherData(systemEventWatcher, row, OnTake);
208     }
209
210     static napi_value RegisterWatcher(napi_env env, napi_callback_info info) {
211         // 开发者自定义观察者名称,系统根据不同的名称来识别不同的观察者。
212         systemEventWatcher = OH_HiAppEvent_CreateWatcher("onTriggerWatcher");
213         // 设置订阅的事件为EVENT_APP_FREEZE。
214         const char *names[] = {EVENT_APP_FREEZE};
215         // 开发者订阅感兴趣的事件,此处订阅了系统事件。
216         OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1);
217         // 开发者设置已实现的回调函数,需OH_HiAppEvent_SetTriggerCondition设置的条件满足方可触发。
218         OH_HiAppEvent_SetWatcherOnTrigger(systemEventWatcher, OnTrigger);
219         // 开发者可以设置订阅触发回调的条件,此处是设置新增事件打点数量为1个时,触发onTrigger回调。
220         OH_HiAppEvent_SetTriggerCondition(systemEventWatcher, 1, 0, 0);
221         // 使观察者开始监听订阅的事件。
222         OH_HiAppEvent_AddWatcher(systemEventWatcher);
223         return {};
224     }
225     ```
226
2275. 将RegisterWatcher注册为ArkTS接口:
228
229   编辑"napi_init.cpp"文件,将RegisterWatcher注册为ArkTS接口:
230
231   ```c++
232   static napi_value Init(napi_env env, napi_value exports)
233   {
234       napi_property_descriptor desc[] = {
235           { "registerWatcher", nullptr, RegisterWatcher, nullptr, nullptr, nullptr, napi_default, nullptr }
236       };
237       napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
238       return exports;
239   }
240   ```
241
242   编辑"index.d.ts"文件,定义ArkTS接口:
243
244   ```typescript
245   export const registerWatcher: () => void;
246   ```
247
2486. 编辑"EntryAbility.ets"文件,在onCreate()函数中新增接口调用:
249
250   ```typescript
251   // 导入依赖模块
252   import testNapi from 'libentry.so'
253
254   // 在onCreate()函数中新增接口调用
255   // 启动时,注册系统事件观察者
256   testNapi.registerWatcher();
257   ```
258
2597. 编辑"Index.ets"文件,新增按钮触发卡顿事件:
260
261   ```typescript
262   Button("appFreeze").onClick(() => {
263     setTimeout(()=>{
264       while(true) {}
265     }, 1000)
266   })
267   ```
268
2698. 点击DevEco Studio界面中的运行按钮,运行应用工程,然后在应用界面中点击按钮“appFreeze”,触发一次卡死事件。
270
2719. 应用工程崩溃退出后再次运行可以在Log窗口看到对系统事件数据的处理日志:
272
273   ```text
274   HiAppEvent eventInfo.domain=OS
275   HiAppEvent eventInfo.name=APP_FREEZE
276   HiAppEvent eventInfo.eventType=1
277   HiAppEvent eventInfo.params.time=1502049167732
278   HiAppEvent eventInfo.params.foreground=1
279   HiAppEvent eventInfo.params.bundle_version=1.0.0
280   HiAppEvent eventInfo.params.bundle_name=com.example.myapplication
281   HiAppEvent eventInfo.params.process_name=com.example.myapplication
282   HiAppEvent eventInfo.params.pid=1587
283   HiAppEvent eventInfo.params.uid=20010043
284   HiAppEvent eventInfo.params.uuid=a78a23b20f3dd9730f18a5cfa2304deac1104ac4086755c4a59cf7c72d414e2e
285   HiAppEvent eventInfo.params.exception={"message":"App main thread is not response!","name":"THREAD_BLOCK_6S"}
286   HiAppEvent eventInfo.params.hilog.size=6
287   HiAppEvent eventInfo.params.event_handler.size=16
288   HiAppEvent eventInfo.params.event_handler_3s.size=15
289   HiAppEvent eventInfo.params.event_handler_6s.size=16
290   HiAppEvent eventInfo.params.peer_binder.size=0
291   HiAppEvent eventInfo.params.threads.size=28
292   HiAppEvent eventInfo.params.memory={"pss":0,"rss":0,"sys_avail_mem":1326520,"sys_free_mem":940588,"sys_total_mem":1992340,"vss":0}
293   HiAppEvent eventInfo.params.external_log=["/data/storage/el2/log/hiappevent/APP_FREEZE_1502049185239_1587.log"]
294   HiAppEvent eventInfo.params.log_over_limit=0
295   ```
296
29710. 移除事件观察者:
298
299    ```c++
300    static napi_value RemoveWatcher(napi_env env, napi_callback_info info) {
301        // 使观察者停止监听事件
302        OH_HiAppEvent_RemoveWatcher(systemEventWatcher);
303        return {};
304    }
305    ```
306
30711. 销毁事件观察者:
308
309    ```c++
310    static napi_value DestroyWatcher(napi_env env, napi_callback_info info) {
311        // 销毁创建的观察者,并置systemEventWatcher为nullptr。
312        OH_HiAppEvent_DestroyWatcher(systemEventWatcher);
313        systemEventWatcher = nullptr;
314        return {};
315    }
316    ```
317