1# AppStartup 2<!--Kit: Ability Kit--> 3<!--Subsystem: Ability--> 4<!--Owner: @yzkp--> 5<!--Designer: @yzkp--> 6<!--Tester: @lixueqing513--> 7<!--Adviser: @huipeizi--> 8 9## Overview 10 11During application launch, a series of startup tasks are often required. If all these tasks are placed within the [onCreate](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md#oncreate) lifecycle of the [UIAbility](../reference/apis-ability-kit/js-apis-app-ability-uiAbility.md) in the [HAP](../quick-start/hap-package.md), they can only be executed sequentially on the main thread, which significantly affects the application launch speed. In addition, when there are too many tasks, complex dependencies between them make the code difficult to maintain. 12 13AppStartup offers an efficient approach to application launch. By supporting asynchronous initiation of startup tasks, it ensures a smoother startup process. The centralized configuration of execution order and dependencies of multiple startup tasks in a single file simplifies and clarifies the startup codebase, enhancing maintainability. 14 15## Working Mechanism 16 17AppStartup supports startup tasks in automatic or manual mode. By default, automatic mode is used. During the creation of an [AbilityStage](ability-terminology.md#abilitystage), the configured startup tasks are loaded and executed in automatic mode. You can also call [startupManager.run](../reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md#startupmanagerrun) to execute the startup tasks in manual mode after an AbilityStage is created. 18 19**Figure 1** Startup procedure 20 21 22 23 24## Supported Scope 25 26- An entry-type HAP can be started in automatic or manual mode. Starting from API version 20, a feature-type HAP can be started in automatic or manual mode. 27 28- Starting from API version 18, startup tasks can be configured in the [HSP](../quick-start/in-app-hsp.md) and [HAR](../quick-start/har-package.md). However, startup tasks and .so file preloading tasks in the HSP and HAR cannot be set to automatic mode. Instead, they can be initiated by the automatic startup tasks and .so file preloading tasks in the HAP. 29 30- Starting from API version 18, AppStartup supports the configuration of .so file preloading tasks. For details about how to develop .so files, refer to [Node-API](../napi/use-napi-process.md) to create a native C++ project. 31 32 33## Constraints 34 35- AppStartup must be enabled in the [module.json5](../quick-start/module-configuration-file.md) file of the [HAP](../quick-start/hap-package.md). 36 37- Given that the ExtensionAbility have a single launch scenario and using AppStartup will add unnecessary overhead, it is not supported to trigger AppStartup when starting the ExtensionAbility. 38 39- Circular dependencies between startup tasks or .so file preloading tasks are not allowed. 40 41 42## Development Process 43 441. [Defining an AppStartup Configuration File](#defining-an-appstartup-configuration-file): Create and define an AppStartup configuration file in the resource file directory. 45 1. [Creating an AppStartup Configuration File](#creating-an-appstartup-configuration-file): Create an AppStartup configuration file in the resource file directory, and reference this configuration file in [module.json5](../quick-start/module-configuration-file.md). 46 2. [Defining Startup Parameter Configuration](#defining-startup-parameter-configuration): Add startup parameter configuration information to the AppStartup configuration file. 47 3. [Defining Startup Task Configuration](#defining-startup-task-configuration): Add startup task configuration information to the AppStartup configuration file. 48 4. [Defining .so File Preloading Task Configuration](#defining-so-file-preloading-task-configuration): Add configuration information of .so file preloading tasks to the AppStartup configuration file. 49 502. [Setting Startup Parameters](#setting-startup-parameters): In the startup parameter file, set parameters such as the timeout interval and startup task listener. 513. [Adding a Startup Task for Each Component to Be Initialized](#adding-a-startup-task-for-each-component-to-be-initialized): Implement the [StartupTask](../reference/apis-ability-kit/js-apis-app-appstartup-startupTask.md) interface. 524. [Optional Operations](optional-operations): You can finely control the behavior of AppStartup in complex scenarios. 53 - [Using AppStartup in the HSP and HAR](#using-appstartup-in-the-hsp-and-har): Configure startup tasks and .so file preloading tasks in the HSP and HAR to manage dependencies across modules, making large applications start faster and be easier to maintain. 54 - [Changing Startup Mode](#changing-startup-mode): Switch the startup task and .so file preloading task to manual mode to decide exactly when they run, cutting down on startup time. 55 - [Adding Task Matching Rules](#adding-task-matching-rules): Use rules to filter which tasks run, ensuring only relevant tasks load based on the situation. 56 57 58## Defining an AppStartup Configuration File 59 60### Creating an AppStartup Configuration File 61 621. Create an AppStartup configuration file in **resources/base/profile** of the [HAP](../quick-start/hap-package.md). The file name can be customized. The following uses **startup_config.json** as an example. 63 642. Add the index of the AppStartup configuration file to the **appStartup** tag in the [module.json5 file](../quick-start/module-configuration-file.md). 65 66 The following is an example of the **module.json5** file: 67 68 ```json 69 { 70 "module": { 71 "name": "entry", 72 "type": "entry", 73 // ... 74 "appStartup": "$profile:startup_config," // AppStartup configuration file 75 // ... 76 } 77 } 78 ``` 79 80### Defining Startup Parameter Configuration 81 82In the **startup_config.json** file, add the configuration for the startup parameters. 83 841. Create the startup parameter configuration file in the **ets/startup** directory. In this example, the file name is **StartupConfig.ets**. 852. Add the information about the startup parameter configuration file to the **startup_config.json** file. 86 87 The following is an example of the **startup_config.json** file: 88 89 ```json 90 { 91 "startupTasks": [ 92 // A startup task. 93 ], 94 "appPreloadHintStartupTasks": [ 95 // A .so file preloading task. 96 ], 97 "configEntry": "./ets/startup/StartupConfig.ets" // Startup parameter configuration. 98 } 99 ``` 100 101**Table 1** Fields in the startup_config.json file 102 103| Field| Description| Data Type| Optional| 104| -------- | -------- | -------- | -------- | 105| startupTasks | Configuration information about a startup task. For details, see [Defining Startup Task Configuration](#defining-startup-task-configuration).| Object array| Optional, defaults to an empty array| 106| appPreloadHintStartupTasks | Configuration information about a .so file preloading task configuration. For details, see [Defining .so File Preloading Task Configuration](#defining-so-file-preloading-task-configuration).| Object array| Optional, defaults to an empty array| 107| configEntry | Path of the startup parameter file. For details, see [Setting Startup Parameters](#setting-startup-parameters).<br>**NOTE**<br>- Do not configure this field for the HSP and HAR.<br>- If [file name obfuscation](../arkts-utils/source-obfuscation.md#-enable-filename-obfuscation) is enabled, the file path must be added to the trustlist. For details, see [-keep-file-name](../arkts-utils/source-obfuscation.md#-keep-file-name).| String| Mandatory| 108 109### Defining Startup Task Configuration 110 111It is assumed that the application has six startup tasks. The dependencies between the tasks are shown in the figure below. To facilitate concurrent execution of startup tasks, a startup task file should contain only one startup task. In this example, each startup task corresponds to a startup task file. 112 113**Figure 2** Dependencies between startup tasks 114 115 116 1171. Create six startup task files in the **ets/startup** directory. The file names must be unique. In this example, the six files are named from **StartupTask_001.ets** to **StartupTask_006.ets**. 1182. Add the startup task configuration information to the **startup_config.json** file. 119 120 The following is an example of the **startup_config.json** file: 121 122 ```json 123 { 124 "startupTasks": [ 125 { 126 "name": "StartupTask_001", 127 "srcEntry": "./ets/startup/StartupTask_001.ets", 128 "dependencies": [ 129 "StartupTask_002", 130 "StartupTask_003" 131 ], 132 "runOnThread": "taskPool", 133 "waitOnMainThread": false 134 }, 135 { 136 "name": "StartupTask_002", 137 "srcEntry": "./ets/startup/StartupTask_002.ets", 138 "dependencies": [ 139 "StartupTask_003", 140 "StartupTask_004" 141 ], 142 "runOnThread": "taskPool", 143 "waitOnMainThread": false 144 }, 145 { 146 "name": "StartupTask_003", 147 "srcEntry": "./ets/startup/StartupTask_003.ets", 148 "dependencies": [ 149 "StartupTask_004" 150 ], 151 "runOnThread": "taskPool", 152 "waitOnMainThread": false 153 }, 154 { 155 "name": "StartupTask_004", 156 "srcEntry": "./ets/startup/StartupTask_004.ets", 157 "runOnThread": "taskPool", 158 "waitOnMainThread": false 159 }, 160 { 161 "name": "StartupTask_005", 162 "srcEntry": "./ets/startup/StartupTask_005.ets", 163 "dependencies": [ 164 "StartupTask_006" 165 ], 166 "runOnThread": "mainThread", 167 "waitOnMainThread": true, 168 "excludeFromAutoStart": true 169 }, 170 { 171 "name": "StartupTask_006", 172 "srcEntry": "./ets/startup/StartupTask_006.ets", 173 "runOnThread": "mainThread", 174 "waitOnMainThread": false, 175 "excludeFromAutoStart": true 176 } 177 ], 178 "appPreloadHintStartupTasks": [ 179 // A .so file preloading file. 180 ], 181 "configEntry": "./ets/startup/StartupConfig.ets" 182 } 183 ``` 184 185**Table 2** Description of startupTasks 186 187| Field| Description| Data Type| Optional| 188| -------- | -------- | -------- | -------- | 189| name | Name of the startup task, which can be customized. It is recommended that the name be the same as the class name.| String| Mandatory| 190| srcEntry | Path of the file corresponding to the startup task.<br>**NOTE**<br> If [file name obfuscation](../arkts-utils/source-obfuscation.md#-enable-filename-obfuscation) is enabled, the file path must be added to the trustlist. For details, see [-keep-file-name](../arkts-utils/source-obfuscation.md#-keep-file-name).| String| Mandatory| 191| dependencies | Array holding the class names of other startup tasks on which this task depends.| Object array| Optional, defaults to an empty array| 192| excludeFromAutoStart | Whether to exclude automatic mode. For details, see [Changing Startup Mode](#changing-startup-mode).<br>- **true**: manual mode.<br>- **false**: automatic mode.<br>**NOTE**<br> This field must be set to **true** for the HSP and HAR.| Boolean| Optional, defaults to **false**| 193| runOnThread | Thread where the startup task is executed.<br>- **mainThread**: executed in the main thread.<br>- **taskPool**: executed in an asynchronous thread.| String| Optional, defaults to **mainThread**| 194| waitOnMainThread | Whether the main thread needs to wait until the startup task finishes execution. This parameter is valid only when **runOnThread** is set to **taskPool**.<br>- **true**: The main thread loads the application home page only the startup task finishes execution.<br>- **false**: The main thread does not wait for the startup task to finish execution.| Boolean| Optional, defaults to **true**| 195| matchRules | Used to filter startup tasks that should be initiated in automatic mode to expedite the application launch process. It is ideal for scenarios where you need to quickly pull up a particular page, such as transitions triggered by home screen widgets, notifications, or intent calls, to provide a seamless one-step experience for accessing functional services. For details, see [Adding Task Matching Rules](#adding-task-matching-rules).<br>**NOTE**<br>- This field is supported since API version 20 and can be configured only in HAPs.<br>- This field takes precedence over **excludeFromAutoStart**. If none of the startup tasks match, the tasks are processed according to their **excludeFromAutoStart** settings.| Object| Optional| 196 197### Defining .so File Preloading Task Configuration 198 199It is assumed that AppStartup has six .so file preloading tasks. The dependencies between the tasks are shown in the figure below. You are not advised to run code logic in the loading callback of .so files, as prolonged .so file loading can adversely affect the main thread's operation. 200 201**Figure 3** Dependencies between .so file preloading tasks 202 203 204 2051. Create.so files by referring to [Node-API](../napi/use-napi-process.md). In this example, the six files are named from **libentry_001.so** to **libentry_006.so**. 2062. Add the configuration information of the .so file preloading tasks to the **startup_config.json** file. 207 208 The following is an example of the **startup_config.json** file: 209 210 ```json 211 { 212 "startupTasks": [ 213 // A startup task. 214 ], 215 "appPreloadHintStartupTasks": [ 216 { 217 "name": "libentry_001", 218 "srcEntry": "libentry_001.so", 219 "dependencies": [ 220 "libentry_002", 221 "libentry_003" 222 ], 223 "runOnThread": "taskPool" 224 }, 225 { 226 "name": "libentry_002", 227 "srcEntry": "libentry_002.so", 228 "dependencies": [ 229 "libentry_003", 230 "libentry_004" 231 ], 232 "runOnThread": "taskPool" 233 }, 234 { 235 "name": "libentry_003", 236 "srcEntry": "libentry_003.so", 237 "dependencies": [ 238 "libentry_004" 239 ], 240 "runOnThread": "taskPool" 241 }, 242 { 243 "name": "libentry_004", 244 "srcEntry": "libentry_004.so", 245 "runOnThread": "taskPool" 246 }, 247 { 248 "name": "libentry_005", 249 "srcEntry": "libentry_005.so", 250 "dependencies": [ 251 "libentry_006" 252 ], 253 "runOnThread": "taskPool", 254 "excludeFromAutoStart": true 255 }, 256 { 257 "name": "libentry_006", 258 "srcEntry": "libentry_006.so", 259 "runOnThread": "taskPool", 260 "excludeFromAutoStart": true 261 } 262 ], 263 "configEntry": "./ets/startup/StartupConfig.ets" 264 } 265 ``` 266 267**Table 3** appPreloadHintStartupTasks 268 269| Field| Description| Data Type| Optional| 270| -------- | -------- | -------- | -------- | 271| name | Name of the .so file to preload.| String| Mandatory| 272| srcEntry | File name of the .so file, including the extension.| String| Mandatory| 273| dependencies | Array holding the .so file names of other preloading tasks on which this task depends.| Object array| Optional, defaults to an empty array| 274| excludeFromAutoStart | Whether to exclude automatic mode. For details, see [Changing Startup Mode](#changing-startup-mode).<br>- **true**: manual mode.<br>- **false**: automatic mode.<br>**NOTE**<br> This field must be set to **true** for the HSP and HAR.| Boolean| Optional, defaults to **false**| 275| runOnThread | Thread where preloading is performed.<br>- **taskPool**: executed in an asynchronous thread.<br>**NOTE**<br> Preloading of .so files can be executed only in TaskPool threads.| String| Mandatory| 276| matchRules | Used to filter the .so file preloading tasks that should be initiated in automatic mode to expedite the application launch process. It is ideal for scenarios where you need to quickly pull up a particular page, such as transitions triggered by home screen widgets, notifications, or intent calls, to provide a seamless one-step experience for accessing functional services. For details, see [Adding Task Matching Rules](#adding-task-matching-rules).<br>**NOTE**<br>- This field is supported since API version 20 and can be configured only in HAPs.<br>- The priority of this field is higher than that of **excludeFromAutoStart**. If none of the .so file preloading tasks match, the tasks are processed according to their **excludeFromAutoStart** settings.| Object| Optional| 277 278## Setting Startup Parameters 279 280In the startup parameter file (**ets/startup/StartupConfig.ets** in this example), call [StartupConfigEntry](../reference/apis-ability-kit/js-apis-app-appstartup-startupConfigEntry.md) to set the common AppStartup parameters, including the timeout interval and listener. 281 282- [StartupConfig](../reference/apis-ability-kit/js-apis-app-appstartup-startupConfig.md): sets the task timeout interval and AppStartup listener. 283- [StartupListener](../reference/apis-ability-kit/js-apis-app-appstartup-startupListener.md): listens for the execution result of the startup task. 284 285```ts 286import { StartupConfig, StartupConfigEntry, StartupListener } from '@kit.AbilityKit'; 287import { hilog } from '@kit.PerformanceAnalysisKit'; 288import { BusinessError } from '@kit.BasicServicesKit'; 289 290export default class MyStartupConfigEntry extends StartupConfigEntry { 291 onConfig() { 292 hilog.info(0x0000, 'testTag', `onConfig`); 293 let onCompletedCallback = (error: BusinessError<void>) => { 294 hilog.info(0x0000, 'testTag', `onCompletedCallback`); 295 if (error) { 296 hilog.error(0x0000, 'testTag', 'onCompletedCallback: %{public}d, message: %{public}s', error.code, error.message); 297 } else { 298 hilog.info(0x0000, 'testTag', `onCompletedCallback: success.`); 299 } 300 }; 301 let startupListener: StartupListener = { 302 'onCompleted': onCompletedCallback 303 }; 304 let config: StartupConfig = { 305 'timeoutMs': 10000, 306 'startupListener': startupListener 307 }; 308 return config; 309 } 310} 311``` 312 313 314## Adding a Startup Task for Each Component to Be Initialized 315 316Through the preceding operations, you have configured the AppStartup configuration file and startup parameters. Now you need to implement [StartupTask](../reference/apis-ability-kit/js-apis-app-appstartup-startupTask.md) in each startup task file by calling the following two APIs: 317 318- [init](../reference/apis-ability-kit/js-apis-app-appstartup-startupTask.md#init): starts task initialization. Call **init** to initialize a task only after all startup tasks on which the task depends are executed, that is, after **onDependencyCompleted** is invoked. 319- [onDependencyCompleted](../reference/apis-ability-kit/js-apis-app-appstartup-startupTask.md#ondependencycompleted): invoked when the startup task on which the current task depends is complete. 320 321 322The following uses the **StartupTask_001.ets** file in [startup_config.json](#defining-startup-task-configuration) as an example. You must add a startup task for each component to be initialized. 323 324> **NOTE** 325> 326> **StartupTask** follows the [Sendable protocol](../arkts-utils/arkts-sendable.md#sendable-protocol). Therefore, the Sendable annotation must be added when this API is inherited. 327 328```ts 329import { StartupTask, common } from '@kit.AbilityKit'; 330import { hilog } from '@kit.PerformanceAnalysisKit'; 331 332@Sendable 333export default class StartupTask_001 extends StartupTask { 334 constructor() { 335 super(); 336 } 337 338 async init(context: common.AbilityStageContext) { 339 hilog.info(0x0000, 'testTag', 'StartupTask_001 init.'); 340 return 'StartupTask_001'; 341 } 342 343 onDependencyCompleted(dependence: string, result: Object): void { 344 hilog.info(0x0000, 'testTag', 'StartupTask_001 onDependencyCompleted, dependence: %{public}s, result: %{public}s', 345 dependence, JSON.stringify(result)); 346 } 347} 348``` 349 350## Optional Operations 351 352 ### Using AppStartup in the HSP and HAR 353 354 Large applications often consist of multiple [HSP](../quick-start/in-app-hsp.md) and [HAR](../quick-start/har-package.md) modules. This section provides an example to demonstrate how to use AppStartup in HSP and HAR packages. This example application includes two HSP packages (hsp1, hsp2) and one HAR package (har1), with startup tasks and .so file preloading tasks. 355 356 Perform the following steps: 357 358 1. Create an AppStartup configuration file under the **resources/base/profile** directory for each HSP and HAR, in addition to the [HAP](../quick-start/hap-package.md). Different modules can use the same file name. The following uses **startup_config.json** as an example. 359 360 2. Configure the **startup_config.json** file for each module. 361 362 The table below lists the startup tasks and .so file preloading tasks available for the application. 363 364 **Table 4** Startup tasks and .so file preloading tasks 365 | Module| Startup Task| .so File Preloading Task| 366 | ------- | -------------------------------- | -------------------------------- | 367 | entry | HAP_Task_01 | libentry_01 | 368 | hsp1 | HSP1_Task_01 <br> HSP1_Task_02 | libhsp1_01 <br> libhsp1_02 | 369 | hsp2 | HSP2_Task_01 | libhsp2_01 | 370 | har | HAR1_Task_01 | libhar1_01 | 371 372 **Figure 4** Dependencies between the startup tasks and .so file preloading tasks 373 374  375 376 For details about the **startup_config.json** file of the [HAP](../quick-start/hap-package.md), see [Defining Startup Task Configuration](#defining-startup-task-configuration). For the HSP and HAR, do not configure the **configEntry** field in the **startup_config.json** file. The following uses the configuration file of **hsp1** as an example: 377 378 ```json 379 { 380 "startupTasks": [ 381 { 382 "name": "HSP1_Task_01", 383 "srcEntry": "./ets/startup/HSP1_Task_01.ets", 384 "dependencies": [ 385 "HSP1_Task_02", 386 "HAR1_Task_01" 387 ], 388 "runOnThread": "taskPool", 389 "waitOnMainThread": false, 390 "excludeFromAutoStart": true 391 } 392 ], 393 "appPreloadHintStartupTasks": [ 394 { 395 "name": "libhsp1_01", 396 "srcEntry": "libhsp1_01.so", 397 "dependencies": [ 398 "libhsp1_02", 399 "libhar1_01" 400 ], 401 "runOnThread": "taskPool", 402 "excludeFromAutoStart": true 403 } 404 ] 405 } 406 ``` 407 408 3. Add the index of the AppStartup configuration file to the **appStartup** tag in the [module.json5 file](../quick-start/module-configuration-file.md) of each module. 409 410 The following are examples of **module.json5** for **hsp1**, **hsp2**, and **har1**: 411 412 ```json 413 { 414 "module": { 415 "name": "hsp1", 416 "type": "shared", 417 // ... 418 "appStartup": "$profile:startup_config," // AppStartup configuration file 419 // ... 420 } 421 } 422 ``` 423 ```json 424 { 425 "module": { 426 "name": "hsp2", 427 "type": "shared", 428 // ... 429 "appStartup": "$profile:startup_config," // AppStartup configuration file 430 // ... 431 } 432 } 433 ``` 434 ```json 435 { 436 "module": { 437 "name": "har1", 438 "type": "har", 439 // ... 440 "appStartup": "$profile:startup_config," // AppStartup configuration file 441 // ... 442 } 443 } 444 ``` 445 446For details about other steps, see [Setting Startup Parameters](#setting-startup-parameters) and [Adding a Startup Task for Each Component to Be Initialized](#adding-a-startup-task-for-each-component-to-be-initialized). 447 448 449### Changing Startup Mode 450 451AppStartup provides two modes for executing startup tasks: automatic and manual. The entry module defaults to automatic mode, but you can change it to manual mode if needed. The HSP and HAR support the configuration of manual mode only. 452 453- Automatic mode: After an AbilityStage is created, startup tasks are automatically executed. 454- Manual mode: After a UIAbility is created, you need to manually call the API to execute the startup tasks and .so file preloading tasks. Modules that are infrequently used do not need to be initialized when the application is launched. You can change the startup mode of these modules to manual. After the application finishes launching, you can call [startupManager.run](../reference/apis-ability-kit/js-apis-app-appstartup-startupManager.md#startupmanagerrun) to execute the startup tasks and .so file preloading tasks. 455 456The following uses the **onCreate** lifecycle of the UIAbility as an example to describe how to manually trigger a startup task. The sample code is as follows: 457 458```ts 459import { AbilityConstant, UIAbility, Want, startupManager } from '@kit.AbilityKit'; 460import { hilog } from '@kit.PerformanceAnalysisKit'; 461import { BusinessError } from '@kit.BasicServicesKit'; 462 463export default class EntryAbility extends UIAbility { 464 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void { 465 hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate'); 466 let startParams = ['StartupTask_005', 'StartupTask_006']; 467 try { 468 startupManager.run(startParams).then(() => { 469 console.log(`StartupTest startupManager run then, startParams = ${JSON.stringify(startParams)}.`); 470 }).catch((error: BusinessError) => { 471 console.error(`StartupTest promise catch error, error = ${JSON.stringify(error)}.`); 472 console.error(`StartupTest promise catch error, startParams = ${JSON.stringify(startParams)}.`); 473 }) 474 } catch (error) { 475 let errMsg = (error as BusinessError).message; 476 let errCode = (error as BusinessError).code; 477 console.error(`Startup catch error, errCode= ${errCode}.`); 478 console.error(`Startup catch error, errMsg= ${errMsg}.`); 479 } 480 } 481 482 // ... 483} 484``` 485 486You can also call the API to trigger the manual mode after a page is loaded. The sample code is as follows: 487 488```ts 489import { startupManager } from '@kit.AbilityKit'; 490 491@Entry 492@Component 493struct Index { 494 @State message: string = "Manual Mode"; 495 @State startParams1: Array<string> = ["StartupTask_006"]; 496 @State startParams2: Array<string> = ["libentry_006"]; 497 498 build() { 499 RelativeContainer() { 500 Button(this.message) 501 .id('AppStartup') 502 .fontSize(20) 503 .fontWeight(FontWeight.Bold) 504 .onClick(() => { 505 if (!startupManager.isStartupTaskInitialized("StartupTask_006") ) { // Check whether the startup task finishes execution. 506 startupManager.run(this.startParams1) 507 } 508 if (!startupManager.isStartupTaskInitialized("libentry_006") ) { 509 startupManager.run(this.startParams2) 510 } 511 }) 512 .alignRules({ 513 center: {anchor: '__container__', align: VerticalAlign.Center}, 514 middle: {anchor: '__container__', align: HorizontalAlign.Center} 515 }) 516 } 517 .height('100%') 518 .width('100%') 519 } 520} 521``` 522 523### Adding Task Matching Rules 524 525To achieve a one-step direct experience for functional services when launching a specific page via methods such as widgets, notifications, or intent calls, you can use **matchRules** to load only the relevant startup tasks for the current scenario, instead of loading all default auto-start tasks. This approach enhances startup performance. 526 527You can add match rules in either of the following ways: 528 529* Using **uris**, **actions**, and **insightIntents** fields in **matchRules**: Match different startup tasks and .so file preloading tasks based on the URI, action, or intent name when the UIAbility is launched. 530* Using **customization** in **matchRules**: If the above methods do not meet your needs, you can define custom matching rule. 531 532 **Table 5** Description of matchRules fields 533 534 | Field| Description| Data Type| Optional| Scenario| 535 | -------- | -------- | -------- | -------- | -------- | 536 | uris | Range of URIs for tasks executed in automatic mode. When the UIAbility is launched, **uri** in the [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md) is matched against the configured **uris** array. The format is `scheme://host/path`, and other parts of the URI (such as port and fragment) are ignored.| String array| Optional, defaults to empty| The UIAbility is started through a specific URI.| 537 | actions | Range of actions for tasks executed in automatic mode. When the UIAbility is launched, **action** in the [Want](../reference/apis-ability-kit/js-apis-app-ability-want.md) is matched against the configured **actions** array.| String array| Optional, defaults to empty| The UIAbility is started through a specific action.| 538 | insightIntents | Range of intent names for tasks executed in automatic mode. When the UIAbility is launched, **intentName** is matched against the configured **insightIntents** array.| String array| Optional, defaults to empty| The UIAbility is started through a specific intent name.| 539 | customization | Range of custom rules for tasks executed in automatic mode. Custom rules are returned by [onRequestCustomMatchRule](../reference/apis-ability-kit/js-apis-app-appstartup-startupConfigEntry.md#startupconfigentryonrequestcustommatchrule20) of StartupConfigEntry. When the UIAbility is started, the custom rule is matched against the configured **customization** array.<br>**NOTE**<br>Only tasks in **startupTasks** are supported.| String array| Optional, defaults to empty| If the **uris**, **actions**, and **insightIntents** fields do not meet your needs, you can use **customization** to customize rules.| 540 541 > **NOTE** 542 > 543 > * If any of **uris**, **actions**, **insightIntents**, or **customization** match, the task is considered matched. 544 > * If any task matches, the task and its dependent tasks will be executed in automatic mode. 545 > * If all tasks fail to match, they are handled according to their **excludeFromAutoStart** configuration. 546 547The following uses URI matching (similar to action and intent name matching) and customization matching as examples to describe how to add task matching rules to filter tasks. 548 549**Scenario 1: URI Matching** 550 551Suppose you want to automatically execute StartupTask_004 and libentry_006 tasks when a user taps a notification to jump to the notification details page. If **uri** in the Want when launching the notification details UIAbility is `test://com.example.startupdemo/notification`, you can match it via URI. Here is an example: 552 5531. Modify the **startup_config.json** file in [Defining Startup Task Configuration](#defining-startup-task-configuration) to add **matchRules** for StartupTask_004 and libentry_006. 554 555 ```json 556 { 557 "startupTasks": [ 558 { 559 "name": "StartupTask_004", 560 "srcEntry": "./ets/startup/StartupTask_004.ets", 561 "runOnThread": "taskPool", 562 "waitOnMainThread": false, 563 "matchRules": { 564 "uris": [ 565 "test://com.example.startupdemo/notification" 566 ] 567 } 568 }, 569 ], 570 "appPreloadHintStartupTasks": [ 571 { 572 "name": "libentry_006", 573 "srcEntry": "libentry_006.so", 574 "runOnThread": "taskPool", 575 "excludeFromAutoStart": true, 576 "matchRules": { 577 "uris": [ 578 "test://com.example.startupdemo/notification" 579 ] 580 } 581 } 582 ], 583 "configEntry": "./ets/startup/StartupConfig.ets" 584 } 585 ``` 586 587**Scenario 2: Customization Matching** 588 589Suppose you want to automatically execute StartupTask_006 and .so file preloading tasks with **excludeFromAutoStart=false** when a user taps a weather widget to jump to the weather screen. If the custom parameter **fromType** in the Want when launching the weather UIAbility is **card**, you can match it via customization. Here is an example: 590 591 1. Modify the **MyStartupConfigEntry.ets** file in [Setting Startup Parameters](#setting-startup-parameters) and add [onRequestCustomMatchRule](../reference/apis-ability-kit/js-apis-app-appstartup-startupConfigEntry.md#startupconfigentryonrequestcustommatchrule20). 592 593 ```ts 594 import { StartupConfig, StartupConfigEntry, StartupListener, Want } from '@kit.AbilityKit'; 595 import { hilog } from '@kit.PerformanceAnalysisKit'; 596 import { BusinessError } from '@kit.BasicServicesKit'; 597 598 export default class MyStartupConfigEntry extends StartupConfigEntry { 599 600 // onConfig ... 601 602 onRequestCustomMatchRule(want: Want): string { 603 if (want?.parameters?.fromType == 'card') { 604 return 'ruleCard'; 605 } 606 return ''; 607 } 608 609 } 610 ``` 611 612 2. Modify the **startup_config.json** file in [Defining Startup Task Configuration](#defining-startup-task-configuration) to add **matchRules** for StartupTask_006. The .so file preloading task does not support the **customization** field and is handled according to the **excludeFromAutoStart** configuration. 613 614 ```json 615 { 616 "startupTasks": [ 617 { 618 "name": "StartupTask_006", 619 "srcEntry": "./ets/startup/StartupTask_006.ets", 620 "runOnThread": "mainThread", 621 "waitOnMainThread": false, 622 "excludeFromAutoStart": true, 623 "matchRules": { 624 "customization": [ 625 "ruleCard" 626 ] 627 } 628 } 629 ], 630 "configEntry": "./ets/startup/StartupConfig.ets" 631 } 632 ``` 633