1# Subscribing to Application Freeze Events (C/C++) 2 3## Overview 4 5The following describes how to subscribe to application freeze events by using the C/C++ APIs provided by HiAppEvent. 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 17 18The following describes how to subscribe to the application freeze event triggered by button clicking. 19 201. Create a native C++ project and import the **jsoncpp** file to the project. The directory structure is as follows: 21 22 ```yml 23 entry: 24 src: 25 main: 26 cpp: 27 json: 28 - json.h 29 - json-forwards.h 30 types: 31 libentry: 32 - index.d.ts 33 - CMakeLists.txt 34 - jsoncpp.cpp 35 - napi_init.cpp 36 ets: 37 entryability: 38 - EntryAbility.ets 39 pages: 40 - Index.ets 41 ``` 42 432. In the **CMakeLists.txt** file, add the source file and dynamic libraries. 44 45 ```cmake 46 # Add the jsoncpp.cpp file, which is used to parse the JSON strings in the subscription events. 47 add_library(entry SHARED napi_init.cpp jsoncpp.cpp) 48 # Add libhiappevent_ndk.z.so and libhilog_ndk.z.so (log output). 49 target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libhiappevent_ndk.z.so) 50 ``` 51 523. Import the dependencies to the **napi_init.cpp** file, and define **LOG_TAG**. 53 54 ```c++ 55 #include "napi/native_api.h" 56 #include "json/json.h" 57 #include "hilog/log.h" 58 #include "hiappevent/hiappevent.h" 59 60 #undef LOG_TAG 61 #define LOG_TAG "testTag" 62 ``` 63 644. Subscribe to system events. 65 66 - Watcher of the **onReceive** type. 67 68 In the **napi_init.cpp** file, define the methods related to **onReceive()**. 69 70 ```c++ 71 // Define a variable to cache the pointer to the created watcher. 72 static HiAppEvent_Watcher *systemEventWatcher; 73 74 static void OnReceive(const char *domain, const struct HiAppEvent_AppEventGroup *appEventGroups, uint32_t groupLen) { 75 for (int i = 0; i < groupLen; ++i) { 76 for (int j = 0; j < appEventGroups[i].infoLen; ++j) { 77 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", appEventGroups[i].appEventInfos[j].domain); 78 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", appEventGroups[i].appEventInfos[j].name); 79 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", appEventGroups[i].appEventInfos[j].type); 80 if (strcmp(appEventGroups[i].appEventInfos[j].domain, DOMAIN_OS) == 0 && 81 strcmp(appEventGroups[i].appEventInfos[j].name, EVENT_APP_FREEZE) == 0) { 82 Json::Value params; 83 Json::Reader reader(Json::Features::strictMode()); 84 Json::FastWriter writer; 85 if (reader.parse(appEventGroups[i].appEventInfos[j].params, params)) { 86 auto time = params["time"].asInt64(); 87 auto foreground = params["foreground"].asBool(); 88 auto bundleVersion = params["bundle_version"].asString(); 89 auto bundleName = params["bundle_name"].asString(); 90 auto processName = params["process_name"].asString(); 91 auto pid = params["pid"].asInt(); 92 auto uid = params["uid"].asInt(); 93 auto uuid = params["uuid"].asString(); 94 auto exception = writer.write(params["exception"]); 95 auto hilogSize = params["hilog"].size(); 96 auto handleSize = params["event_handler"].size(); 97 auto handleSize3s = params["event_handler_size_3s"].asString(); 98 auto handleSize6s = params["event_handler_size_6s"].asString(); 99 auto peerBindSize = params["peer_binder"].size(); 100 auto threadSize = params["threads"].size(); 101 auto memory = writer.write(params["memory"]); 102 auto externalLog = writer.write(params["external_log"]); 103 auto logOverLimit = params["log_over_limit"].asBool(); 104 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time); 105 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.foreground=%{public}d", foreground); 106 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str()); 107 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_name=%{public}s", bundleName.c_str()); 108 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str()); 109 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid); 110 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid); 111 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str()); 112 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str()); 113 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize); 114 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler.size=%{public}d", handleSize); 115 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler_3s.size=%{public}s", handleSize3s.c_str()); 116 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler_6s.size=%{public}s", handleSize6s.c_str()); 117 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize); 118 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.threads.size=%{public}d", threadSize); 119 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str()); 120 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str()); 121 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit); 122 } 123 } 124 } 125 } 126 } 127 128 static napi_value RegisterWatcher(napi_env env, napi_callback_info info) { 129 // Set the watcher name. The system identifies different watchers based on their names. 130 systemEventWatcher = OH_HiAppEvent_CreateWatcher("onReceiverWatcher"); 131 // Set the event to watch to EVENT_APP_FREEZE. 132 const char *names[] = {EVENT_APP_FREEZE}; 133 // Add the events to watch, for example, system events. 134 OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1); 135 // Set the implemented callback. After receiving the event, the watcher immediately triggers the OnReceive callback. 136 OH_HiAppEvent_SetWatcherOnReceive(systemEventWatcher, OnReceive); 137 // Add a watcher to listen for the specified event. 138 OH_HiAppEvent_AddWatcher(systemEventWatcher); 139 return {}; 140 } 141 ``` 142 143 - Watcher of the **onTrigger** type. 144 145 In the **napi_init.cpp** file, define the methods related to **OnTrigger()**. 146 147 ```c++ 148 // Define a variable to cache the pointer to the created watcher. 149 static HiAppEvent_Watcher *systemEventWatcher; 150 151 // Implement the callback function used to return the listened events. The content pointed to by the events pointer is valid only in this function. 152 static void OnTake(const char *const *events, uint32_t eventLen) { 153 Json::Reader reader(Json::Features::strictMode()); 154 Json::FastWriter writer; 155 for (int i = 0; i < eventLen; ++i) { 156 Json::Value eventInfo; 157 if (reader.parse(events[i], eventInfo)) { 158 auto domain = eventInfo["domain_"].asString(); 159 auto name = eventInfo["name_"].asString(); 160 auto type = eventInfo["type_"].asInt(); 161 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", domain.c_str()); 162 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", name.c_str()); 163 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", type); 164 if (domain == DOMAIN_OS && name == EVENT_APP_FREEZE) { 165 auto time = eventInfo["time"].asInt64(); 166 auto foreground = eventInfo["foreground"].asBool(); 167 auto bundleVersion = eventInfo["bundle_version"].asString(); 168 auto bundleName = eventInfo["bundle_name"].asString(); 169 auto processName = eventInfo["process_name"].asString(); 170 auto pid = eventInfo["pid"].asInt(); 171 auto uid = eventInfo["uid"].asInt(); 172 auto uuid = eventInfo["uuid"].asString(); 173 auto exception = writer.write(eventInfo["exception"]); 174 auto hilogSize = eventInfo["hilog"].size(); 175 auto handleSize = eventInfo["event_handler"].size(); 176 auto handleSize3s = eventInfo["event_handler_size_3s"].asString(); 177 auto handleSize6s = eventInfo["event_handler_size_6s"].asString(); 178 auto peerBindSize = eventInfo["peer_binder"].size(); 179 auto threadSize = eventInfo["threads"].size(); 180 auto memory = writer.write(eventInfo["memory"]); 181 auto externalLog = writer.write(eventInfo["external_log"]); 182 auto logOverLimit = eventInfo["log_over_limit"].asBool(); 183 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.time=%{public}lld", time); 184 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.foreground=%{public}d", foreground); 185 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", bundleVersion.c_str()); 186 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_name=%{public}s", bundleName.c_str()); 187 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.process_name=%{public}s", processName.c_str()); 188 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.pid=%{public}d", pid); 189 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid); 190 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uuid=%{public}s", uuid.c_str()); 191 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.exception=%{public}s", exception.c_str()); 192 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.hilog.size=%{public}d", hilogSize); 193 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler.size=%{public}d", handleSize); 194 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler_3s.size=%{public}s", handleSize3s.c_str()); 195 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.event_handler_6s.size=%{public}s", handleSize6s.c_str()); 196 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.peer_binder.size=%{public}d", peerBindSize); 197 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.threads.size=%{public}d", threadSize); 198 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.memory=%{public}s", memory.c_str()); 199 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str()); 200 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", logOverLimit); 201 } 202 } 203 } 204 } 205 206 // Implement the subscription callback function to apply custom processing to the obtained event logging data. 207 static void OnTrigger(int row, int size) { 208 // After the callback is received, obtain the specified number of received events. 209 OH_HiAppEvent_TakeWatcherData(systemEventWatcher, row, OnTake); 210 } 211 212 static napi_value RegisterWatcher(napi_env env, napi_callback_info info) { 213 // Set the watcher name. The system identifies different watchers based on their names. 214 systemEventWatcher = OH_HiAppEvent_CreateWatcher("onTriggerWatcher"); 215 // Set the event to watch to EVENT_APP_FREEZE. 216 const char *names[] = {EVENT_APP_FREEZE}; 217 // Add the events to watch, for example, system events. 218 OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1); 219 // Set the implemented callback function. The callback function will be triggered when the conditions set by OH_HiAppEvent_SetTriggerCondition are met. 220 OH_HiAppEvent_SetWatcherOnTrigger(systemEventWatcher, OnTrigger); 221 // Set the conditions for triggering the subscription callback. For example, trigger this onTrigger callback when the number of new event logs is 1. 222 OH_HiAppEvent_SetTriggerCondition(systemEventWatcher, 1, 0, 0); 223 // Add a watcher to listen for the specified event. 224 OH_HiAppEvent_AddWatcher(systemEventWatcher); 225 return {}; 226 } 227 ``` 228 2295. Register **RegisterWatcher** as an ArkTS API. 230 231 In the **napi_init.cpp** file, register **RegisterWatcher** as an ArkTS API. 232 233 ```c++ 234 static napi_value Init(napi_env env, napi_value exports) 235 { 236 napi_property_descriptor desc[] = { 237 { "registerWatcher", nullptr, RegisterWatcher, 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 244 In the **index.d.ts** file, define the ArkTS API. 245 246 ```typescript 247 export const registerWatcher: () => void; 248 ``` 249 2506. In the **EntryAbility.ets** file, add the following API to **onCreate()**. 251 252 ```typescript 253 // Import the dependent module. 254 import testNapi from 'libentry.so' 255 256 // Add the API to onCreate(). 257 // Register the system event watcher at startup. 258 testNapi.registerWatcher(); 259 ``` 260 2617. In the **Index.ets** file, add a button to trigger the freeze event. 262 263 ```typescript 264 Button("appFreeze").onClick(() => { 265 setTimeout(()=>{ 266 while(true) {} 267 }, 1000) 268 }) 269 ``` 270 2718. In DevEco Studio, click the **Run** button to run the project. Then, click the **appfreeze** button to trigger an application freeze event. 272 273### Verifying the Subscription 274 2751. The application crashes. After restarting the application, you can view the following event information in the **Log** window. 276 277 ```text 278 HiAppEvent eventInfo.domain=OS 279 HiAppEvent eventInfo.name=APP_FREEZE 280 HiAppEvent eventInfo.eventType=1 281 HiAppEvent eventInfo.params.time=1502049167732 282 HiAppEvent eventInfo.params.foreground=1 283 HiAppEvent eventInfo.params.bundle_version=1.0.0 284 HiAppEvent eventInfo.params.bundle_name=com.example.myapplication 285 HiAppEvent eventInfo.params.process_name=com.example.myapplication 286 HiAppEvent eventInfo.params.pid=1587 287 HiAppEvent eventInfo.params.uid=20010043 288 HiAppEvent eventInfo.params.uuid=a78a23b20f3dd9730f18a5cfa2304deac1104ac4086755c4a59cf7c72d414e2e 289 HiAppEvent eventInfo.params.exception={"message":"App main thread is not response!","name":"THREAD_BLOCK_6S"} 290 HiAppEvent eventInfo.params.hilog.size=6 291 HiAppEvent eventInfo.params.event_handler.size=16 292 HiAppEvent eventInfo.params.event_handler_3s.size=15 293 HiAppEvent eventInfo.params.event_handler_6s.size=16 294 HiAppEvent eventInfo.params.peer_binder.size=0 295 HiAppEvent eventInfo.params.threads.size=28 296 HiAppEvent eventInfo.params.memory={"pss":0,"rss":0,"sys_avail_mem":1326520,"sys_free_mem":940588,"sys_total_mem":1992340,"vss":0} 297 HiAppEvent eventInfo.params.external_log=["/data/storage/el2/log/hiappevent/APP_FREEZE_1502049185239_1587.log"] 298 HiAppEvent eventInfo.params.log_over_limit=0 299 ``` 300 301### Removing and Destroying an Event Watcher 302 3031. Remove the event watcher. 304 305 ```c++ 306 static napi_value RemoveWatcher(napi_env env, napi_callback_info info) { 307 // Remove the watcher. 308 OH_HiAppEvent_RemoveWatcher(systemEventWatcher); 309 return {}; 310 } 311 ``` 312 3132. Destroy the event watcher. 314 315 ```c++ 316 static napi_value DestroyWatcher(napi_env env, napi_callback_info info) { 317 // Destroy the created watcher and set systemEventWatcher to nullptr. 318 OH_HiAppEvent_DestroyWatcher(systemEventWatcher); 319 systemEventWatcher = nullptr; 320 return {}; 321 } 322 ``` 323