• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Event Subscription (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 provides APIs for subscribing to application events.
11
12## Available APIs
13
14For details about how to use the APIs (such as parameter usage restrictions and value ranges), see [hiappevent.h](../reference/apis-performance-analysis-kit/capi-hiappevent-h.md).
15
16**Subscription APIs**
17
18| API| Description|
19| -------- | -------- |
20| int OH_HiAppEvent_AddWatcher(HiAppEvent_Watcher \* watcher) | Adds a watcher to listen for application events.|
21| int OH_HiAppEvent_RemoveWatcher(HiAppEvent_Watcher \* watcher) | Removes a watcher for the specified application events.|
22
23**Event Logging APIs**
24
25| API| Description|
26| -------- | -------- |
27| int OH_HiAppEvent_Write(const char \* domain, const char \* name, enum EventType type, const ParamList list) | Logs application events whose parameters are of the list type.|
28
29## How to Develop
30
31The following describes how to subscribe to a crash event (system event) and a button click event (application event).
32
33### Step 1: Creating a Project and Configuring Compilation Options
34
351. Obtain the **jsoncpp** file on which the sample project depends.
36   Specifically, download the source code package from [JsonCpp](https://github.com/open-source-parsers/jsoncpp) and obtain the **jsoncpp.cpp**, **json.h**, and **json-forwards.h** files by following the procedure described in **Amalgamated source**.
37   Create a native C++ project and import the **jsoncpp** file to the project. The directory structure is as follows:
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. In the **CMakeLists.txt** file, add the source file and dynamic libraries.
62
63   ```cmake
64   # Add the jsoncpp.cpp file, which is used to parse the JSON strings in the subscription events.
65   add_library(entry SHARED napi_init.cpp jsoncpp.cpp)
66   # Add libhiappevent_ndk.z.so and libhilog_ndk.z.so (log output).
67   target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libhiappevent_ndk.z.so)
68   ```
69
703. Import the dependencies to the **napi_init.cpp** file, and define **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### Step 2: Subscribing to an Event
83
841. Subscribe to the events using **OnReceive** and **OnTrigger**, respectively.
85   - Subscribe to the crash event (system event) using **OnReceive**. After receiving the event, the watcher immediately triggers the **OnReceive** callback. In the **napi_init.cpp** file, define the methods related to the watcher of the **OnReceive** type.
86
87      ```c++
88      // Define a variable to cache the pointer to the created watcher.
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                          // Obtain the timestamp of the crash event.
104                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", params["time"].asInt64());
105                          // Obtain the bundle name of the crashed application.
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                          // Obtain the error log file about the crash event.
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          // Set the watcher name. The system identifies different watchers based on their names.
117          onReceiverWatcher = OH_HiAppEvent_CreateWatcher("AppCrashWatcher");
118          // Set the event name for subscription to EVENT_APP_CRASH (the crash event).
119          const char *names[] = {EVENT_APP_CRASH};
120          // Add the events to watch, for example, system events.
121          OH_HiAppEvent_SetAppEventFilter(onReceiverWatcher, DOMAIN_OS, 0, names, 1);
122          // Set the implemented callback. After receiving the event, the watcher immediately triggers the OnReceive callback.
123          OH_HiAppEvent_SetWatcherOnReceive(onReceiverWatcher, OnReceive);
124          // Add a watcher to listen for the specified event.
125          OH_HiAppEvent_AddWatcher(onReceiverWatcher);
126          return {};
127      }
128      ```
129
130   - Subscribes to the button click event (application event) using **OnTrigger**. The **OnTrigger()** callback can be triggered only when the conditions specified by **OH_HiAppEvent_SetTriggerCondition()** are met. In the **napi_init.cpp** file, define the methods related to the watcher of the **OnTrigger** type.
131
132      ```c++
133      // Define a variable to cache the pointer to the created watcher.
134      static HiAppEvent_Watcher *onTriggerWatcher;
135      // Implement the callback function used to return the listened events. The content pointed to by the events pointer is valid only in this function.
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      // Implement the subscription callback function to apply custom processing to the obtained event logging data.
157      static void OnTrigger(int row, int size) {
158          // After the callback is received, obtain the specified number of received events.
159          OH_HiAppEvent_TakeWatcherData(onTriggerWatcher, row, OnTake);
160      }
161
162      static napi_value RegisterWatcherClick(napi_env env, napi_callback_info info) {
163          // Set the watcher name. The system identifies different watchers based on their names.
164          onTriggerWatcher = OH_HiAppEvent_CreateWatcher("ButtonClickWatcher");
165          // Set the name of the subscribed event to click.
166          const char *names[] = {"click"};
167          // Add the system events to watch, for example, events related to button.
168          OH_HiAppEvent_SetAppEventFilter(onTriggerWatcher, "button", 0, names, 1);
169          // Set the implemented callback function. The callback function will be triggered when the conditions set by OH_HiAppEvent_SetTriggerCondition are met.
170          OH_HiAppEvent_SetWatcherOnTrigger(onTriggerWatcher, OnTrigger);
171          // Set the conditions for triggering the subscription callback. For example, trigger this onTrigger callback when the number of new event logs is 1.
172          OH_HiAppEvent_SetTriggerCondition(onTriggerWatcher, 1, 0, 0);
173          // Add a watcher to listen for the specified event.
174          OH_HiAppEvent_AddWatcher(onTriggerWatcher);
175          return {};
176      }
177      ```
178
1792. In the **napi_init.cpp** file, add the logging API for the button click event.
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. In the **napi_init.cpp** file, register **RegisterWatcherCrash()** (crash event subscription), **RegisterWatcherClick()** (button click event subscription), and **WriteAppEvent()** (button click event logging) as ArkTS APIs.
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. In the **index.d.ts** file, define the ArkTS API.
207
208   ```ts
209   export const registerWatcherCrash: () => void;
210   export const registerWatcherClick: () => void;
211   export const writeAppEvent: () => void;
212   ```
213
2145. In the **EntryAbility.ets** file, add the following API to **onCreate()**.
215
216   ```ts
217   // Import the dependent module.
218   import testNapi from 'libentry.so';
219
220   // Add the API call to onCreate().
221   // Register the crash event watcher at startup.
222   testNapi.registerWatcherCrash();
223   // Register the button click event watcher at startup.
224   testNapi.registerWatcherClick();
225   ```
226
227### Step 3: Triggering an Event
228
229In the **Index.ets** file, add the **appCrash** button to trigger the crash event, and add the **buttonClick** button to log events in the button click function. The sample code is as follows:
230
231```ts
232// Import the dependent module.
233import testNapi from 'libentry.so';
234
235@Entry
236@Component
237struct Index {
238  build() {
239    Row() {
240      Column() {
241        Button("appCrash")
242          .onClick(() => {
243            // Construct a scenario in onClick() to trigger a crash event.
244            let result: object = JSON.parse("");
245          })
246          .position({ x: 100, y: 100 }) // Set the button position.
247
248        Button("buttonClick")
249          .onClick(() => {
250            // Log a button click event when the button is clicked.
251            testNapi.writeAppEvent();
252          })
253          .position({ x: 100, y: 200 }) // Set the button position.
254        }
255      .width('100%')
256    }
257    .height('100%')
258  }
259}
260```
261
262## Debugging and Verification
263
2641. Click the **Run** button in DevEco Studio to run the project. Then, click the **appCrash** button to trigger a crash event. After the application exits, restart it.
265
2662. Search for the keyword **HiAppEvent** in the HiLog window to view the logs of the crash event processing.
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. Click the **buttonClick** button to trigger the button click event. Search for the keyword **HiAppEvent** in the HiLog window to view the logs of the button click event processing.
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. Remove the application event watcher.
288
289   ```c++
290   static napi_value RemoveWatcher(napi_env env, napi_callback_info info) {
291       // Remove the watcher.
292       OH_HiAppEvent_RemoveWatcher(appEventWatcher);
293       return {};
294   }
295   ```
296
2975. Destroy the application event watcher.
298
299   ```c++
300   static napi_value DestroyWatcher(napi_env env, napi_callback_info info) {
301       // Destroy the created watcher and set appEventWatcher to nullptr.
302       OH_HiAppEvent_DestroyWatcher(appEventWatcher);
303       appEventWatcher = nullptr;
304       return {};
305   }
306   ```
307