1# 订阅主线程超时事件(C/C++) 2 3<!--Kit: Performance Analysis Kit--> 4<!--Subsystem: HiviewDFX--> 5<!--Owner: @rr_cn--> 6<!--Designer: @peterhuangyu--> 7<!--Tester: @gcw_KuLfPSbe--> 8<!--Adviser: @foryourself--> 9 10## 简介 11 12本文介绍如何使用HiAppEvent提供的C/C++接口订阅主线程超时事件。接口的详细使用说明(参数限制、取值范围等)请参考[HiAppEvent C API文档](../reference/apis-performance-analysis-kit/capi-hiappevent-h.md)。 13 14## 接口说明 15 16| 接口名 | 描述 | 17| -------- | -------- | 18| int OH_HiAppEvent_AddWatcher(HiAppEvent_Watcher \*watcher) | 添加应用事件观察者,以添加对应用事件的订阅。 | 19| int OH_HiAppEvent_RemoveWatcher(HiAppEvent_Watcher \*watcher) | 移除应用事件观察者,以移除对应用事件的订阅。 | 20 21## 开发步骤 22 23### 添加事件观察者 241. 参考[三方开源库jsoncpp代码仓](https://github.com/open-source-parsers/jsoncpp)README中**Using JsonCpp in your project**介绍的使用方法获取到jsoncpp.cpp、json.h和json-forwards.h三个文件。 25 262. 新建Native C++工程,并将上述文件导入到新建工程内,目录结构如下。 27 28 ```yml 29 entry: 30 src: 31 main: 32 cpp: 33 json: 34 - json.h 35 - json-forwards.h 36 types: 37 libentry: 38 - index.d.ts 39 - CMakeLists.txt 40 - jsoncpp.cpp 41 - napi_init.cpp 42 ets: 43 entryability: 44 - EntryAbility.ets 45 pages: 46 - Index.ets 47 ``` 48 493. 编辑“CMakeLists.txt”文件,添加源文件及动态库。 50 51 ```cmake 52 # 新增jsoncpp.cpp(解析订阅事件中的json字符串)源文件 53 add_library(entry SHARED napi_init.cpp jsoncpp.cpp) 54 # 新增动态库依赖libhiappevent_ndk.z.so和libhilog_ndk.z.so(日志输出) 55 target_link_libraries(entry PUBLIC libace_napi.z.so libhilog_ndk.z.so libhiappevent_ndk.z.so) 56 ``` 57 584. 编辑“napi_init.cpp”文件,导入依赖的文件,并定义LOG_TAG。 59 60 ```c++ 61 #include "napi/native_api.h" 62 #include "json/json.h" 63 #include "hilog/log.h" 64 #include "hiappevent/hiappevent.h" 65 #include "hiappevent/hiappevent_event.h" 66 #undef LOG_TAG 67 #define LOG_TAG "testTag" 68 ``` 69 705. 订阅系统事件。 71 72 - onReceive类型观察者 73 74 编辑“napi_init.cpp”文件,定义onReceive类型观察者相关方法: 75 76 ```c++ 77 //定义一变量,用来缓存创建的观察者的指针。 78 static HiAppEvent_Watcher *systemEventWatcher; 79 80 static void OnReceive(const char *domain, const struct HiAppEvent_AppEventGroup *appEventGroups, uint32_t groupLen) { 81 for (int i = 0; i < groupLen; ++i) { 82 for (int j = 0; j < appEventGroups[i].infoLen; ++j) { 83 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.domain=%{public}s", 84 appEventGroups[i].appEventInfos[j].domain); 85 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.name=%{public}s", 86 appEventGroups[i].appEventInfos[j].name); 87 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.eventType=%{public}d", 88 appEventGroups[i].appEventInfos[j].type); 89 if (strcmp(appEventGroups[i].appEventInfos[j].domain, DOMAIN_OS) == 0 && 90 strcmp(appEventGroups[i].appEventInfos[j].name, EVENT_MAIN_THREAD_JANK) == 0) { 91 Json::Value params; 92 Json::Reader reader(Json::Features::strictMode()); 93 Json::FastWriter writer; 94 if (reader.parse(appEventGroups[i].appEventInfos[j].params, params)) { 95 auto time = params["time"].asInt64(); 96 auto pid = params["pid"].asInt(); 97 auto uid = params["uid"].asInt(); 98 auto bundleName = params["bundle_name"].asString(); 99 auto bundleVersion = params["bundle_version"].asString(); 100 auto beginTime = params["begin_time"].asInt64(); 101 auto endTime = params["end_time"].asInt64(); 102 auto externalLog = writer.write(params["external_log"]); 103 auto logOverLimit = params["logOverLimit"].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.pid=%{public}d", pid); 106 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.uid=%{public}d", uid); 107 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_name=%{public}s", 108 bundleName.c_str()); 109 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.bundle_version=%{public}s", 110 bundleVersion.c_str()); 111 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.begin_time=%{public}lld", beginTime); 112 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.end_time=%{public}lld", endTime); 113 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.external_log=%{public}s", externalLog.c_str()); 114 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent eventInfo.params.log_over_limit=%{public}d", 115 logOverLimit); 116 } 117 } 118 } 119 } 120 } 121 122 static napi_value RegisterWatcher(napi_env env, napi_callback_info info) { 123 OH_LOG_INFO(LogType::LOG_APP, "HiAppEvent RegisterWatcher"); 124 // 开发者自定义观察者名称,系统根据不同的名称来识别不同的观察者。 125 systemEventWatcher = OH_HiAppEvent_CreateWatcher("onReceiverWatcher"); 126 // 设置订阅的事件为EVENT_MAIN_THREAD_JANK。 127 const char *names[] = {EVENT_MAIN_THREAD_JANK}; 128 // 开发者订阅感兴趣的事件,此处订阅了系统事件。 129 OH_HiAppEvent_SetAppEventFilter(systemEventWatcher, DOMAIN_OS, 0, names, 1); 130 // 开发者设置已实现的回调函数,观察者接收到事件后回立即触发OnReceive回调。 131 OH_HiAppEvent_SetWatcherOnReceive(systemEventWatcher, OnReceive); 132 // 使观察者开始监听订阅的事件。 133 OH_HiAppEvent_AddWatcher(systemEventWatcher); 134 return {}; 135 } 136 ``` 137 1386. 将RegisterWatcher注册为ArkTS接口。 139 140 编辑“napi_init.cpp”文件,将RegisterWatcher注册为ArkTS接口: 141 142 ```c++ 143 static napi_value Init(napi_env env, napi_value exports) 144 { 145 napi_property_descriptor desc[] = { 146 { "registerWatcher", nullptr, RegisterWatcher, nullptr, nullptr, nullptr, napi_default, nullptr } 147 }; 148 napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); 149 return exports; 150 } 151 ``` 152 153 编辑“index.d.ts”文件,定义ArkTS接口: 154 155 ```typescript 156 export const registerWatcher: () => void; 157 ``` 158 1597. 编辑工程中的“entry > src > main > ets > entryability> EntryAbility.ets”文件,在onCreate()函数中新增接口调用。 160 161 ```typescript 162 // 导入依赖模块 163 import testNapi from 'libentry.so'; 164 165 // 在onCreate()函数中新增接口调用 166 // 启动时,注册系统事件观察者 167 testNapi.registerWatcher(); 168 ``` 169 1708. 编辑工程中的“entry > src > main > ets > pages> Index.ets”文件,添加一个Button控件onClick中实现主线程超时代码,示例代码如下: 171 172 ```typescript 173 Button("timeOut350") 174 .fontSize(50) 175 .fontWeight(FontWeight.Bold) 176 .onClick(() => { 177 let t = Date.now(); 178 while (Date.now() - t <= 350) {} 179 }) 180 ``` 181 1829. 点击DevEco Studio界面中的运行按钮,运行应用工程,连续点击两次timeOut350按钮,会触发主线程超时事件。 183 184### 验证观察者是否订阅到主线程超时事件 185 1861. 主线程超时事件上报后,可以在Log窗口看到对系统事件数据的处理日志: 187 188 ```text 189 HiAppEvent eventInfo.domain=OS 190 HiAppEvent eventInfo.name=MAIN_THREAD_JANK 191 HiAppEvent eventInfo.eventType=1 192 HiAppEvent eventInfo.params.time=1717597063727 193 HiAppEvent eventInfo.params.pid=45572 194 HiAppEvent eventInfo.params.uid=20020151 195 HiAppEvent eventInfo.params.bundle_name=com.example.nativemainthread 196 HiAppEvent eventInfo.params.bundle_version=1.0.0 197 HiAppEvent eventInfo.params.begin_time=1717597063225 198 HiAppEvent eventInfo.params.end_time=1717597063727 199 HiAppEvent eventInfo.params.external_log=["/data/storage/el2/log/watchdog/MAIN_THREAD_JANK_20240613221239_45572.txt"] 200 HiAppEvent eventInfo.params.log_over_limit=0 201 ``` 202 203 > **说明:** 204 > 205 > 主线程超时事件具体规格可参考:[主线程超时事件默认时间规格](apptask-timeout-guidelines.md#检测原理) 和 [主线程超时事件日志规格](apptask-timeout-guidelines.md#日志规格)。 206 207### 移除并销毁事件观察者 208 2091. 移除事件观察者: 210 211 ```c++ 212 static napi_value RemoveWatcher(napi_env env, napi_callback_info info) { 213 // 使观察者停止监听事件 214 OH_HiAppEvent_RemoveWatcher(systemEventWatcher); 215 return {}; 216 } 217 ``` 218 2192. 销毁事件观察者: 220 221 ```c++ 222 static napi_value DestroyWatcher(napi_env env, napi_callback_info info) { 223 // 销毁创建的观察者,并置systemEventWatcher为nullptr。 224 OH_HiAppEvent_DestroyWatcher(systemEventWatcher); 225 systemEventWatcher = nullptr; 226 return {}; 227 } 228 ``` 229