• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Subscribing to Main Thread Jank Events (C/C++)
2
3## Overview
4
5This topic describes how to use the C/C++ APIs provided by HiAppEvent to subscribe to main thread jank events. For details (such as parameter restrictions and value ranges), see [hiappevent.h](../reference/apis-performance-analysis-kit/capi-hiappevent-h.md).
6
7## Available APIs
8
9| API| Description|
10| -------- | -------- |
11| int OH_HiAppEvent_AddWatcher(HiAppEvent_Watcher \*watcher) | Adds a watcher to listen for application events.|
12| int OH_HiAppEvent_RemoveWatcher(HiAppEvent_Watcher \*watcher) | Removes a watcher to unsubscribe from application events.|
13
14## How to Develop
15
16### Adding an Event Watcher
171. Obtain the **jsoncpp.cpp**, **json.h**, and **json-forwards.h** files by referring to **Using JsonCpp in your project** in [the third-party open-source library JsonCpp](https://github.com/open-source-parsers/jsoncpp).
18
192. Create a native C++ project and import the preceding files to the project. The directory structure is as follows:
20
21   ```yml
22   entry:
23     src:
24       main:
25         cpp:
26           json:
27             - json.h
28             - json-forwards.h
29           types:
30             libentry:
31               - index.d.ts
32           - CMakeLists.txt
33           - jsoncpp.cpp
34           - napi_init.cpp
35         ets:
36           entryability:
37             - EntryAbility.ets
38           pages:
39             - Index.ets
40   ```
41
423. In the **CMakeLists.txt** file, add the source file and dynamic libraries.
43
44   ```cmake
45   # Add the jsoncpp.cpp file, which is used to parse the JSON strings in the subscription events.
46   add_library(entry SHARED napi_init.cpp jsoncpp.cpp)
47   # Add libhiappevent_ndk.z.so and libhilog_ndk.z.so (log output).
48   target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libhiappevent_ndk.z.so)
49   ```
50
514. Import the dependencies to the **napi_init.cpp** file, and define **LOG_TAG**.
52
53   ```c++
54   #include "napi/native_api.h"
55   #include "json/json.h"
56   #include "hilog/log.h"
57   #include "hiappevent/hiappevent.h"
58   #include "hiappevent/hiappevent_event.h"
59   #undef LOG_TAG
60   #define LOG_TAG "testTag"
61   ```
62
635. Subscribe to system events.
64
65   - Watcher of the **onReceive** type.
66
67      In the **napi_init.cpp** file, define the methods related to the watcher of the **onReceive** type.
68
69      ```c++
70      // Define a variable to cache the pointer to the created watcher.
71      static HiAppEvent_Watcher *systemEventWatcher;
72
73      static void OnReceive(const char *domain, const struct HiAppEvent_AppEventGroup *appEventGroups, uint32_t groupLen) {
74          for (int i = 0; i < groupLen; ++i) {
75              for (int j = 0; j < appEventGroups[i].infoLen; ++j) {
76                  OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s",
77                              appEventGroups[i].appEventInfos[j].domain);
78                  OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s",
79                              appEventGroups[i].appEventInfos[j].name);
80                  OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d",
81                              appEventGroups[i].appEventInfos[j].type);
82                  if (strcmp(appEventGroups[i].appEventInfos[j].domain, DOMAIN_OS) == 0 &&
83                      strcmp(appEventGroups[i].appEventInfos[j].name, EVENT_MAIN_THREAD_JANK) == 0) {
84                      Json::Value params;
85                      Json::Reader reader(Json::Features::strictMode());
86                      Json::FastWriter writer;
87                      if (reader.parse(appEventGroups[i].appEventInfos[j].params, params)) {
88                          auto time = params["time"].asInt64();
89                          auto pid = params["pid"].asInt();
90                          auto uid = params["uid"].asInt();
91                          auto bundleName = params["bundle_name"].asString();
92                          auto bundleVersion = params["bundle_version"].asString();
93                          auto beginTime = params["begin_time"].asInt64();
94                          auto endTime = params["end_time"].asInt64();
95                          auto externalLog = writer.write(params["external_log"]);
96                          auto logOverLimit = params["logOverLimit"].asBool();
97                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time);
98                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid);
99                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid);
100                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_name=%{public}s",
101                                      bundleName.c_str());
102                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s",
103                                      bundleVersion.c_str());
104                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.begin_time=%{public}lld", beginTime);
105                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.end_time=%{public}lld", endTime);
106                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str());
107                          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d",
108                                      logOverLimit);
109                      }
110                  }
111              }
112          }
113      }
114
115      static napi_value RegisterWatcher(napi_env env, napi_callback_info info) {
116          OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent RegisterWatcher");
117          // Set the watcher name. The system identifies different watchers based on their names.
118          systemEventWatcher = OH_HiAppEvent_CreateWatcher("onReceiverWatcher");
119          // Set the event to subscribe to EVENT_MAIN_THREAD_JANK.
120          const char *names[] = {EVENT_MAIN_THREAD_JANK};
121          // Add the events to watch, for example, system events.
122          OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1);
123          // Set the implemented callback. After receiving the event, the watcher immediately triggers the OnReceive callback.
124          OH_HiAppEvent_SetWatcherOnReceive(systemEventWatcher, OnReceive);
125          // Add a watcher to listen for the specified event.
126          OH_HiAppEvent_AddWatcher(systemEventWatcher);
127          return {};
128      }
129      ```
130
1316. Register **RegisterWatcher** as an ArkTS API.
132
133   In the **napi_init.cpp** file, register **RegisterWatcher** as an ArkTS API.
134
135   ```c++
136   static napi_value Init(napi_env env, napi_value exports)
137   {
138       napi_property_descriptor desc[] = {
139           { "registerWatcher", nullptr, RegisterWatcher, nullptr, nullptr, nullptr, napi_default, nullptr }
140       };
141       napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
142       return exports;
143   }
144   ```
145
146   In the **index.d.ts** file, define the ArkTS API.
147
148   ```typescript
149   export const registerWatcher: () => void;
150   ```
151
1527. In the **entry/src/main/ets/entryability/EntryAbility.ets** file, add the following API call to **onCreate()**.
153
154   ```typescript
155   // Import the dependent module.
156   import testNapi from 'libentry.so';
157
158   // Add the interface invocation to onCreate().
159   // Register the system event watcher at startup.
160   testNapi.registerWatcher();
161   ```
162
1638. In the **entry/src/main/ets/pages/Index.ets** file, add the **timeOut500** button with **onClick()** to trigger a main thread jank event when the button is clicked. The sample code is as follows:
164
165   ```typescript
166      Button("timeOut350")
167      .fontSize(50)
168      .fontWeight(FontWeight.Bold)
169      .onClick(() => {
170          let t = Date.now();
171          while (Date.now() - t <= 350) {}
172      })
173   ```
174
1759. In DevEco Studio, click the **Run** button to run the application project. Click the **timeOut350** button twice consecutively to trigger a main thread jank event.
176
177### Verifying the Subscription
178
1791. After the main thread jank event is reported, you can view the following event information in the **Log** window.
180
181   ```text
182     HiAppEvent eventInfo.domain=OS
183     HiAppEvent eventInfo.name=MAIN_THREAD_JANK
184     HiAppEvent eventInfo.eventType=1
185     HiAppEvent eventInfo.params.time=1717597063727
186     HiAppEvent eventInfo.params.pid=45572
187     HiAppEvent eventInfo.params.uid=20020151
188     HiAppEvent eventInfo.params.bundle_name=com.example.nativemainthread
189     HiAppEvent eventInfo.params.bundle_version=1.0.0
190     HiAppEvent eventInfo.params.begin_time=1717597063225
191     HiAppEvent eventInfo.params.end_time=1717597063727
192     HiAppEvent eventInfo.params.external_log=["/data/storage/el2/log/watchdog/MAIN_THREAD_JANK_20240613221239_45572.txt"]
193     HiAppEvent eventInfo.params.log_over_limit=0
194   ```
195
196    > **NOTE**
197    >
198    > For details about the main thread jank event specifications, see [main thread jank event detection principles](apptask-timeout-guidelines.md#detection-principles) and [main thread jank event log specifications](apptask-timeout-guidelines.md#log-specifications).
199
200### Removing and Destroying an Event Watcher
201
2021. Remove the event watcher.
203
204   ```c++
205   static napi_value RemoveWatcher(napi_env env, napi_callback_info info) {
206       // Remove the watcher.
207       OH_HiAppEvent_RemoveWatcher(systemEventWatcher);
208       return {};
209   }
210   ```
211
2122. Destroy the event watcher.
213
214   ```c++
215   static napi_value DestroyWatcher(napi_env env, napi_callback_info info) {
216       // Destroy the created watcher and set systemEventWatcher to nullptr.
217       OH_HiAppEvent_DestroyWatcher(systemEventWatcher);
218       systemEventWatcher = nullptr;
219       return {};
220   }
221   ```
222