1# Event Subscription (ArkTS) 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 [@ohos.hiviewdfx.hiAppEvent (Application Event Logging)](../reference/apis-performance-analysis-kit/js-apis-hiviewdfx-hiappevent.md). 15 16**Subscription APIs** 17 18| API| Description| 19| -------- | -------- | 20| addWatcher(watcher: Watcher): AppEventPackageHolder | Adds a watcher to listen for application events.| 21| removeWatcher(watcher: Watcher): void | Removes a watcher to unsubscribe from application events.| 22 23**Event Logging APIs** 24 25| API| Description| 26| -------- | -------- | 27| write(info: AppEventInfo, callback: AsyncCallback<void>): void | Writes events to the event file through **AppEventInfo** objects. This API uses an asynchronous callback to return the result.| 28| write(info: AppEventInfo): Promise<void> | Writes events to the event file through **AppEventInfo** objects. This API uses a promise to return the result.| 29 30## How to Develop 31 32The following describes how to subscribe to a crash event (system event) and a button click event (application event). 33 341. Create an ArkTS application project. In the **entry/src/main/ets/entryability/EntryAbility.ets** file, import the dependent modules. 35 36 ```ts 37 import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit'; 38 ``` 39 402. In the **entry/src/main/ets/entryability/EntryAbility.ets** file, add the subscription to the crash event and button click event in the **onCreate** function. 41 42 Subscribe to the crash event using **OnReceive**. After receiving the event, the watcher immediately triggers the **OnReceive** callback. In the **EntryAbility.ets** file, define the methods related to the watcher of the **OnReceive** type. 43 44 ```ts 45 hiAppEvent.addWatcher({ 46 // Set the watcher name. The system identifies different watchers based on their names. 47 name: "AppCrashWatcher", 48 // Set the subscription filters. For example, subscribe to the crash event of the system event. 49 appEventFilters: [ 50 { 51 domain: hiAppEvent.domain.OS, 52 names: [hiAppEvent.event.APP_CRASH] 53 } 54 ], 55 // Implement the onReceive callback, which is called in real time after an event is detected. 56 onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => { 57 hilog.info(0x0000, 'testTag', `domain=${domain}`); 58 for (const eventGroup of appEventGroups) { 59 hilog.info(0x0000, 'testTag', `HiAppEvent eventName=${eventGroup.name}`); 60 for (const eventInfo of eventGroup.appEventInfos) { 61 // Obtain the timestamp of the crash event. 62 hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.time=${JSON.stringify(eventInfo.params['time'])}`); 63 // Obtain the bundle name of the crashed application. 64 hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.bundle_name=${JSON.stringify(eventInfo.params['bundle_name'])}`); 65 // Obtain the error log file about the crash event. 66 hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.external_log=${JSON.stringify(eventInfo.params['external_log'])}`); 67 } 68 } 69 } 70 }); 71 ``` 72 73 Subscribe to the button click event using **OnTrigger**. The **OnTrigger()** callback can be triggered only when the conditions specified by **OnTrigger()** are met. In the **napi_init.cpp** file, define the methods related to **OnTrigger()**. 74 75 ```ts 76 hiAppEvent.addWatcher({ 77 // Set the watcher name. The system identifies different watchers based on their names. 78 name: "ButtonClickWatcher", 79 // Add the application events to watch, for example, button onclick events. 80 appEventFilters: [{ domain: "button" }], 81 // Set the subscription callback trigger condition. For example, trigger a callback when one event is logged. 82 triggerCondition: { row: 1 }, 83 // Implement the subscription callback function to apply custom processing to the obtained event logging data. 84 onTrigger: (curRow: number, curSize: number, holder: hiAppEvent.AppEventPackageHolder) => { 85 // If the holder object is null, return after the error is recorded. 86 if (holder == null) { 87 hilog.error(0x0000, 'testTag', "HiAppEvent holder is null"); 88 return; 89 } 90 hilog.info(0x0000, 'testTag', `HiAppEvent onTrigger: curRow=%{public}d, curSize=%{public}d`, curRow, curSize); 91 let eventPkg: hiAppEvent.AppEventPackage | null = null; 92 // Fetch the subscription event package based on the specified threshold (1 event by default) until all subscription event data is fetched. 93 // If all subscription event data is fetched, return a null event package to end this subscription callback. 94 while ((eventPkg = holder.takeNext()) != null) { 95 // Apply custom processing to the event logging data obtained, for example, print the event logging data in the log. 96 hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.packageId=%{public}d`, eventPkg.packageId); 97 hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.row=%{public}d`, eventPkg.row); 98 hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.size=%{public}d`, eventPkg.size); 99 for (const eventInfo of eventPkg.data) { 100 hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.info=%{public}s`, eventInfo); 101 } 102 } 103 } 104 }); 105 ``` 106 1073. In the **entry/src/main/ets/pages/Index.ets** file, import the dependent modules. 108 109 ```ts 110 import { BusinessError } from '@kit.BasicServicesKit'; 111 import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit'; 112 ``` 113 1144. In the **entry/src/main/ets/pages/Index.ets** file, add the **appCrash** button to trigger a crash event and add the **buttonClick** button to log events in the button click function. The sample code is as follows: 115 116 Trigger a crash event. 117 118 ```ts 119 Button("appCrash") 120 .onClick(()=>{ 121 // Construct a scenario in onClick() to trigger a crash event. 122 let result: object = JSON.parse(""); 123 }) 124 .position({ x: 50, y: 100 }) // Set the button position. 125 ``` 126 127 Log events in the button click function. 128 129 ```ts 130 Button("buttonClick") 131 .onClick(()=>{ 132 // In onClick(), use hiAppEvent.write() to log an event when the button is clicked. 133 let eventParams: Record<string, number> = { 'click_time': 100 }; 134 let eventInfo: hiAppEvent.AppEventInfo = { 135 // Define the event domain. 136 domain: "button", 137 // Define the event name. 138 name: "click", 139 // Define the event type. 140 eventType: hiAppEvent.EventType.BEHAVIOR, 141 // Define the event parameters. 142 params: eventParams 143 }; 144 hiAppEvent.write(eventInfo).then(() => { 145 hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`); 146 }).catch((err: BusinessError) => { 147 hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`); 148 }); 149 hilog.info(0x0000, 'testTag', `HiAppEvent write event`); 150 }) 151 .position({ x: 50, y: 200 }) // Set the button position. 152 ``` 153 154## Debugging and Verification 155 1561. 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. 157 1582. Search for the keyword **HiAppEvent** in the **HiLog** window to view logs of crash event processing. 159 160 ```text 161 HiAppEvent eventName=APP_CRASH 162 HiAppEvent eventInfo.params.time=1750747995874 163 HiAppEvent eventInfo.params.bundle_name="com.example.txxxxx" 164 HiAppEvent eventInfo.params.external_log= 165 ["/data/storage/el2/log/hiappevent/APP_CRASH_1750747996042_28962.log"] 166 ``` 167 1683. Click the **Run** button in DevEco Studio to run the project. Then, click the **buttonClick** button to trigger a button click event and perform logging. 169 1704. Search for the keyword **HiAppEvent** in the **HiLog** window to view logs of button click event processing. 171 172 ```text 173 HiAppEvent write event 174 HiAppEvent onTrigger: curRow=1, curSize=121 175 HiAppEvent eventPkg.packageId=0 176 HiAppEvent eventPkg.row=1 177 HiAppEvent eventPkg.size=121 178 HiAppEvent eventPkg.info={"domain_":"button","name_":"click","type_":4,"time_":1750754529033,"tz_":"","pid_":40664,"tid_":40664,"click_time":100} 179 HiAppEvent success to write event 180 ``` 181