• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Subscribing to Task execution timeout events (C/C++)
2
3## Available APIs
4
5For details about how to use the APIs (such as parameter usage restrictions and value ranges), see [HiAppEvent](../reference/apis-performance-analysis-kit/_hi_app_event.md#hiappevent).
6
7**Subscription 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 for the specified application events.|
13
14## How to Develop
15
16The following describes how to subscribe to the freeze event triggered by a button click.
17
181. Create a native C++ project and import the **jsoncpp** file to the project. The directory structure is as follows:
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. In the **CMakeLists.txt** file, add the source file and dynamic libraries.
42
43  ```cmake
44  # Add the jsoncpp.cpp file, which is used to parse the JSON strings in the subscription events.
45  add_library(entry SHARED napi_init.cpp jsoncpp.cpp)
46  # Add libhiappevent_ndk.z.so, libhilog_ndk.z.so (log output), and libohhicollie.so (HiCollie detection).
47  target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libohhicollie.so libhiappevent_ndk.z.so)
48  ```
49
503. Import the dependencies to the **napi_init.cpp** file, and define **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. Subscribe to system events.
63
64    - Watcher of the onReceive type.
65
66    In the **napi_init.cpp** file, define the methods related to the watcher of the **onReceive** type.
67
68    ```c++
69    // Define a variable to cache the pointer to the created watcher.
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_HICOLLIE) == 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 processName = params["process_name"].asString();
88                        auto pid = params["pid"].asInt();
89                        auto uid = params["uid"].asInt();
90                        auto uuid = params["uuid"].asString();
91                        auto exception = writer.write(params["exception"]);
92                        auto hilogSize = params["hilog"].size();
93                        auto peerBindSize =  params["peer_binder"].size();
94                        auto memory =  writer.write(params["memory"]);
95                        auto externalLog = writer.write(params["external_log"]);
96                        auto logOverLimit = params["log_over_limit"].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.foreground=%{public}d", foreground);
99                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str());
100                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str());
101                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid);
102                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid);
103                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str());
104                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str());
105                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize);
106                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize);
107                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str());
108                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str());
109                        OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit);
110                    }
111                }
112            }
113        }
114    }
115
116    static napi_value RegisterWatcher(napi_env env, napi_callback_info info) {
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 watch to EVENT_APP_HICOLLIE.
120        const char *names[] = {EVENT_APP_HICOLLIE};
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
131   - Watcher of the **onTrigger** type:
132
133    In the **napi_init.cpp** file, define the methods related to the watcher of the **OnTrigger** type.
134
135    ```c++
136    // Define a variable to cache the pointer to the created watcher.
137    static HiAppEvent_Watcher *systemEventWatcher;
138
139    // Implement the callback function used to return the listened events. The content pointed to by the events pointer is valid only in this function.
140    static void OnTake(const char *const *events, uint32_t eventLen) {
141        Json::Reader reader(Json::Features::strictMode());
142        Json::FastWriter writer;
143        for (int i = 0; i < eventLen; ++i) {
144            Json::Value eventInfo;
145            if (reader.parse(events[i], eventInfo)) {
146                auto domain =  eventInfo["domain_"].asString();
147                auto name = eventInfo["name_"].asString();
148                auto type = eventInfo["type_"].asInt();
149                OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", domain.c_str());
150                OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", name.c_str());
151                OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", type);
152                if (domain ==  DOMAIN_OS && name == EVENT_APP_HICOLLIE) {
153                    auto time = eventInfo["time"].asInt64();
154                    auto foreground = eventInfo["foreground"].asBool();
155                    auto bundleVersion = eventInfo["bundle_version"].asString();
156                    auto processName = eventInfo["process_name"].asString();
157                    auto pid = eventInfo["pid"].asInt();
158                    auto uid = eventInfo["uid"].asInt();
159                    auto uuid = eventInfo["uuid"].asString();
160                    auto exception = writer.write(eventInfo["exception"]);
161                    auto hilogSize = eventInfo["hilog"].size();
162                    auto peerBindSize =  eventInfo["peer_binder"].size();
163                    auto memory =  writer.write(eventInfo["memory"]);
164                    auto externalLog = writer.write(eventInfo["external_log"]);
165                    auto logOverLimit = eventInfo["log_over_limit"].asBool();
166                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time);
167                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.foreground=%{public}d", foreground);
168                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str());
169                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str());
170                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid);
171                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid);
172                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str());
173                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str());
174                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize);
175                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize);
176                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str());
177                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str());
178                    OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit);
179                }
180            }
181        }
182    }
183
184    // Implement the subscription callback function to apply custom processing to the obtained event logging data.
185    static void OnTrigger(int row, int size) {
186        // After the callback is received, obtain the specified number of received events.
187        OH_HiAppEvent_TakeWatcherData(systemEventWatcher, row, OnTake);
188    }
189
190    static napi_value RegisterWatcher(napi_env env, napi_callback_info info) {
191         // Set the watcher name. The system identifies different watchers based on their names.
192         systemEventWatcher = OH_HiAppEvent_CreateWatcher("onTriggerWatcher");
193         // Set the event to watch to EVENT_APP_HICOLLIE.
194         const char *names[] = {EVENT_APP_HICOLLIE};
195         // Add the events to watch, for example, system events.
196         OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1);
197         // Set the implemented callback function. The callback function will be triggered when the conditions set by OH_HiAppEvent_SetTriggerCondition are met.
198         OH_HiAppEvent_SetWatcherOnTrigger(systemEventWatcher, OnTrigger);
199         // Set the conditions for triggering the subscription callback. For example, trigger this onTrigger callback when the number of new event logs is 1.
200         OH_HiAppEvent_SetTriggerCondition(systemEventWatcher, 1, 0, 0);
201         // Add a watcher to listen for the specified event.
202         OH_HiAppEvent_AddWatcher(systemEventWatcher);
203         return {};
204     }
205     ```
206
2075. Register **RegisterWatcher** as an ArkTS API.
208
209    In the **napi_init.cpp** file, register **RegisterWatcher** as an ArkTS API.
210
211    ```c++
212    static napi_value Init(napi_env env, napi_value exports)
213    {
214        napi_property_descriptor desc[] = {
215           { "registerWatcher", nullptr, RegisterWatcher, nullptr, nullptr, nullptr, napi_default, nullptr },
216        };
217        napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
218        return exports;
219    }
220    ```
221
222    In the **index.d.ts** file, define the ArkTS API.
223
224    ```typescript
225    export const registerWatcher: () => void;
226    ```
227
2286. Register **TestHiCollieTimerNdk** as an ArkTS API.
229
230    In the **napi_init.cpp** file, register **testHiCollieTimerNdk** as an ArkTS API.
231
232    ```c++
233    static napi_value Init(napi_env env, napi_value exports)
234    {
235        napi_property_descriptor desc[] = {
236            { "registerWatcher", nullptr, RegisterWatcher, nullptr, nullptr, nullptr, napi_default, nullptr },
237            { "testHiCollieTimerNdk", nullptr, TestHiCollieTimerNdk, nullptr, nullptr, nullptr, napi_default, nullptr },
238        };
239        napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
240        return exports;
241    }
242
243    // Import the hicollie.h file.
244    #include "hicollie/hicollie.h"
245    static napi_value TestHiCollieTimerNdk(napi_env env, napi_value exports)
246    {
247        // Define the task execution timeout ID.
248        int id;
249        // Define the task timeout detection parameters. When a task times out for 1s, logs are generated.
250        HiCollie_SetTimerParam param = {"testTimer", 1, nullptr, nullptr, HiCollie_Flag::HICOLLIE_FLAG_LOG};
251        // Set the detection.
252        HiCollie_ErrorCode = OH_HiCollie_SetTimer(param, &id);
253        if (errorCode == HICOLLIE_SUCCESS) {
254            OH_LOG_INFO(LogType::LOG_APP, "Timer Id is %{public}d", id);
255            // Construct a timeout interval of 2s.
256            sleep(2);
257            OH_HiCollie_CancelTimer(id);
258        }
259        return 0;
260    }
261    ```
262
2637. In the **EntryAbility.ets** file, add the following API to **onCreate()**.
264
265    ```typescript
266    // Import the dependent module.
267    import testNapi from 'libentry.so'
268
269    // Add the API to onCreate().
270    // Register the system event watcher at startup.
271    testNapi.registerWatcher();
272    ```
273
2748. In the **Index.ets** file, add a button to trigger the task execution timeout event.
275
276    ```typescript
277    Button("testHiCollieTimerNdk")
278      .fontSize(50)
279      .fontWeight(FontWeight.Bold)
280      .onClick(testNapi.testHiCollieTimerNdk);
281    ```
282
2839. In DevEco Studio, click the **Run** button to run the project. Then, click the **testHiCollieTimerNdk** button to trigger a task execution timeout event.
284
28510. The application crashes. After restarting the application, you can view the following event information in the **Log** window.
286
287    ```text
288    HiAppEvent eventInfo.domain=OS
289    HiAppEvent eventInfo.name=APP_HICOLLIE
290    HiAppEvent eventInfo.eventType=1
291    HiAppEvent eventInfo.params.time=1740993639620
292    HiAppEvent eventInfo.params.foreground=1
293    HiAppEvent eventInfo.params.bundle_version=1.0.0
294    HiAppEvent eventInfo.params.process_name=com.example.myapplication
295    HiAppEvent eventInfo.params.pid=26251
296    HiAppEvent eventInfo.params.uid=20020172
297    HiAppEvent eventInfo.params.uuid=4e5d7d0e18f5d6d84cf4f0c9e80d66d0b646c1cc2343d3595f07abb0d3547feb
298    HiAppEvent eventInfo.params.exception={"message":"","name":"APP_HICOLLIE"}
299    HiAppEvent eventInfo.params.hilog.size=77
300    HiAppEvent eventInfo.params.peer_binder.size=18
301    HiAppEvent eventInfo.params.threads.size=28
302    HiAppEvent eventInfo.params.memory={"pss":0,"rss":124668,"sys_avail_mem":2220032,"sys_free_mem":526680,"sys_total_mem":11692576,"vss":4238700}
303    HiAppEvent eventInfo.params.external_log=["/data/storage/el2/log/hiappevent/APP_HICOLLIE_1740993644458_26215.log"]
304    HiAppEvent eventInfo.params.log_over_limit=0
305    ```
306
30711. Remove the event watcher.
308
309    ```c++
310    static napi_value RemoveWatcher(napi_env env, napi_callback_info info) {
311        // Remove the watcher.
312        OH_HiAppEvent_RemoveWatcher(systemEventWatcher);
313        return {};
314    }
315    ```
316
31712. Destroy the event watcher.
318
319    ```c++
320    static napi_value DestroyWatcher(napi_env env, napi_callback_info info) {
321        // Destroy the created watcher and set systemEventWatcher to nullptr.
322        OH_HiAppEvent_DestroyWatcher(systemEventWatcher);
323        systemEventWatcher = nullptr;
324        return {};
325    }
326    ```
327