• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Subscribing to Application Killed Events (ArkTS)
2
3<!--Kit: Performance Analysis Kit-->
4<!--Subsystem: HiviewDFX-->
5<!--Owner: @shead-master-->
6<!--Designer: @peterhuangyu-->
7<!--Tester: @gcw_KuLfPSbe-->
8<!--Adviser: @foryourself-->
9
10## Event Specifications
11
12For details, see [Application Killed Event Overview](./hiappevent-watcher-app-killed-events.md).
13
14## Available APIs
15
16For details about how to use the APIs (such as parameter usage restrictions and value ranges), see [HiAppEvent](../reference/apis-performance-analysis-kit/capi-hiappevent-h.md).
17
18| Name                                             | Description                                        |
19| --------------------------------------------------- | -------------------------------------------- |
20| addWatcher(watcher: Watcher): AppEventPackageHolder | Adds a watcher to listen for application events.|
21| removeWatcher(watcher: Watcher): void               | Removes a watcher for the specified application events.|
22
23## How to Develop
24
25To ensure that the event callback can be successfully received in the development phase, you are advised to create a native C++ project, implement subscription in the ArkTs code, and use the C ++ fault injection code to construct a fault to trigger the application killed event.
26
271. In the **entry/src/main/ets/entryability/EntryAbility.ets** file of the project, import the dependent modules.
28
29   ```ts
30   import { hiAppEvent } from '@kit.PerformanceAnalysisKit';
31   ```
32
332. In the **entry/src/main/ets/entryability/EntryAbility.ets** file, add a watcher in **onCreate()** to subscribe to system events. The sample code is as follows:
34
35   ```ts
36   hiAppEvent.addWatcher({
37     // Set the watcher name. The system identifies different watchers based on their names.
38     name: "watcher",
39     // You can subscribe to system events that you are interested in. Here, the application killed event is subscribed to.
40     appEventFilters: [
41       {
42         domain: hiAppEvent.domain.OS,
43         names: [hiAppEvent.event.APP_KILLED]
44       }
45     ],
46     // Implement a callback for the registered system event so that you can apply custom processing to the event data obtained.
47     onReceive: (domain: string, appEventGroups: Array<hiAppEvent.AppEventGroup>) => {
48       hilog.info(0x0000, 'testTag', `HiAppEvent onReceive: domain=${domain}`);
49       for (const eventGroup of appEventGroups) {
50         // The event name uniquely identifies a system event.
51         hilog.info(0x0000, 'testTag', `HiAppEvent eventName=${eventGroup.name}`);
52         for (const eventInfo of eventGroup.appEventInfos) {
53           // Apply custom processing to the event data obtained, for example, print the event data in the log.
54           hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.domain=${eventInfo.domain}`);
55           hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.name=${eventInfo.name}`);
56           // Obtain the timestamp when the application is killed.
57           hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.time=${eventInfo.params['time']}`);
58           // Obtain the foreground and background status of the application when the killed event occurs.
59           hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.foreground=${eventInfo.params['foreground']}`);
60           // Obtain the cause of the application killed event.
61           hilog.info(0x0000, 'testTag', `HiAppEvent eventInfo.params.reason=${eventInfo.params['reason']}`);
62         }
63       }
64     }
65   });
66   ```
67
683. Edit the **napi_init.cpp** file and add the following code to implement the fault-injection functionality in C++.
69
70   ```C++
71   #include <thread>
72
73   static void NativeLeak()
74   {
75       constexpr int leak_size_per_time = 500000;
76       while (true) {
77           char *p = (char *)malloc(leak_size_per_time + 1);
78           if (!p) {
79               break;
80           }
81           memset(p, 'a', leak_size_per_time);
82           std::this_thread::sleep_for(std::chrono::milliseconds(10));
83       }
84   }
85
86   static napi_value Leak(napi_env env, napi_callback_info info) {
87   	std::thread t1(NativeLeak);
88   	t1.detach();
89       return {};
90   }
91   ```
92
934. In the **napi_init.cpp** file, register **Leak** as an ArkTS API.
94
95   ```c++
96   static napi_value Init(napi_env env, napi_value exports)
97   {
98       napi_property_descriptor desc[] = {
99           { "leak", nullptr, Leak, nullptr, nullptr, nullptr, napi_default, nullptr }, // Add this line.
100       };
101       napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
102       return exports;
103   }
104   ```
105
1065. In the **index.d.ts** file, define the ArkTS API.
107
108   ```ts
109   export const leak: () => void;
110   ```
111
1126. In the **entry/src/main/ets/pages/Index.ets** file,  add the **OnClick** function under **build()** and call the **Leak** API.
113
114   ```ts
115   import { hilog } from '@kit.PerformanceAnalysisKit';
116   import testNapi from 'libentry.so';
117
118   const DOMAIN = 0x0000;
119
120   @Entry
121   @Component
122   struct Index {
123     @State message: string = 'Start To Leak';
124
125     build() {
126       Row() {
127         Column() {
128           Text(this.message)
129             .fontSize($r('app.float.page_text_font_size'))
130             .fontWeight(FontWeight.Bold)
131             .onClick(() => {
132               if (this.message != 'Leaking') {
133                 this.message = 'Leaking';
134                 hilog.info(DOMAIN, 'testTag', 'Start leaking');
135                 testNapi.leak();
136               }
137             })
138         }
139         .width('100%')
140       }
141       .height('100%')
142     }
143   }
144   ```
145
1467. Click the **Run** button in DevEco Studio to run the project. Click **Start To Leak**, and wait for 2 to 3 minutes until **RssThresholdKiller** is triggered.
147
1488. After the application is killed, open the application again. The killed event is reported, and the system calls **onReceive()**. You can view the following event information in the **Log** window.
149
150   Sample stack of the application killed event:
151
152   ```text
153   HiAppEvent eventInfo.domain=OS
154   HiAppEvent eventInfo.name=APP_KILLED
155   HiAppEvent eventInfo.params.time=1717597063727
156   HiAppEvent eventInfo.params.reason="RssThresholdKiller"
157   HiAppEvent eventInfo.params.foreground=true
158   ```
159