1e41f4b71Sopenharmony_ci# Reasonably Running Background Tasks 2e41f4b71Sopenharmony_ci 3e41f4b71Sopenharmony_ci## Introduction 4e41f4b71Sopenharmony_ci 5e41f4b71Sopenharmony_ciWhen you return to the home screen, lock the screen, or switch to another application, the current application is switched to the background. To reduce the device power consumption and deliver a positive user experience, the system manages the application running in the background, for example, suspending or terminating its process. To ensure the normal use of features such as music playback and calendar reminders in the background, the system provides constrained background tasks to extend the running time of applications in the background. 6e41f4b71Sopenharmony_ci 7e41f4b71Sopenharmony_ciThis topic describes the basic concepts and use scenarios of different background tasks, and analyzes the performance of transient tasks and continuous tasks to explain the necessity of properly running background tasks. 8e41f4b71Sopenharmony_ci 9e41f4b71Sopenharmony_ci## Transient Task 10e41f4b71Sopenharmony_ci 11e41f4b71Sopenharmony_ciAn application is suspended after it runs in the background for a short period of time. If the application needs to execute a short-time task in the background, it can request a transient task to extend the running time in the background. 12e41f4b71Sopenharmony_ci 13e41f4b71Sopenharmony_ciTransient tasks are suitable for tasks that have high requirements on real-time performance and occupies resources for a short period of time, for example, small file download, caching, and information sending. For details about the development guide, see [Transient Task](../task-management/transient-task.md). 14e41f4b71Sopenharmony_ci 15e41f4b71Sopenharmony_ci### Example 16e41f4b71Sopenharmony_ci 17e41f4b71Sopenharmony_ciThe following code requests a transient task to execute a time-consuming computing task in the background. The source code is obtained from [Transient Task Sample](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Performance/PerformanceLibrary/feature/backgroundTask/src/main/ets/view/TransientTaskView.ets). 18e41f4b71Sopenharmony_ci 19e41f4b71Sopenharmony_ci```javascript 20e41f4b71Sopenharmony_ciimport backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; 21e41f4b71Sopenharmony_ciimport { BusinessError } from '@ohos.base'; 22e41f4b71Sopenharmony_ciimport util from '@ohos.util'; 23e41f4b71Sopenharmony_ciimport hiTraceMeter from '@ohos.hiTraceMeter'; 24e41f4b71Sopenharmony_ci 25e41f4b71Sopenharmony_ciconst totalTimes: number = 50000000; // Number of loops. 26e41f4b71Sopenharmony_ciconst calculateResult: string ='Total time costed = %s ms.'; // Text format. 27e41f4b71Sopenharmony_ci 28e41f4b71Sopenharmony_ci@Entry 29e41f4b71Sopenharmony_ci@Component 30e41f4b71Sopenharmony_cistruct Index { 31e41f4b71Sopenharmony_ci @State message: string = 'Click button to calculate.'; 32e41f4b71Sopenharmony_ci private requestId: number = 0; 33e41f4b71Sopenharmony_ci 34e41f4b71Sopenharmony_ci // Request a transient task. 35e41f4b71Sopenharmony_ci requestSuspendDelay() { 36e41f4b71Sopenharmony_ci try { 37e41f4b71Sopenharmony_ci let delayInfo = backgroundTaskManager.requestSuspendDelay('compute', () => { 38e41f4b71Sopenharmony_ci console.info('Request suspension delay will time out.'); 39e41f4b71Sopenharmony_ci // Cancel the transient task when the task is about to time out. 40e41f4b71Sopenharmony_ci this.cancelSuspendDelay(); 41e41f4b71Sopenharmony_ci }) 42e41f4b71Sopenharmony_ci this.requestId = delayInfo.requestId; 43e41f4b71Sopenharmony_ci } catch (error) { 44e41f4b71Sopenharmony_ci console.error(`requestSuspendDelay failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 45e41f4b71Sopenharmony_ci } 46e41f4b71Sopenharmony_ci } 47e41f4b71Sopenharmony_ci 48e41f4b71Sopenharmony_ci // Cancel the transient task. 49e41f4b71Sopenharmony_ci cancelSuspendDelay() { 50e41f4b71Sopenharmony_ci backgroundTaskManager.cancelSuspendDelay(this.requestId); 51e41f4b71Sopenharmony_ci console.info('Request suspension delay cancel.'); 52e41f4b71Sopenharmony_ci } 53e41f4b71Sopenharmony_ci 54e41f4b71Sopenharmony_ci // Computing task. 55e41f4b71Sopenharmony_ci computeTask(times: number): number { 56e41f4b71Sopenharmony_ci let start: number = new Date().getTime(); 57e41f4b71Sopenharmony_ci let a: number = 1; 58e41f4b71Sopenharmony_ci let b: number = 1; 59e41f4b71Sopenharmony_ci let c: number = 1; 60e41f4b71Sopenharmony_ci for (let i: number = 0; i < times; i++) { 61e41f4b71Sopenharmony_ci a = a * Math.random() + b * Math.random() + c * Math.random(); 62e41f4b71Sopenharmony_ci b = a * Math.random() + b * Math.random() + c * Math.random(); 63e41f4b71Sopenharmony_ci c = a * Math.random() + b * Math.random() + c * Math.random(); 64e41f4b71Sopenharmony_ci } 65e41f4b71Sopenharmony_ci let end: number = new Date().getTime(); 66e41f4b71Sopenharmony_ci return end - start; 67e41f4b71Sopenharmony_ci } 68e41f4b71Sopenharmony_ci 69e41f4b71Sopenharmony_ci // Configure the touch callback. 70e41f4b71Sopenharmony_ci clickCallback = () => { 71e41f4b71Sopenharmony_ci this.requestSuspendDelay(); 72e41f4b71Sopenharmony_ci hiTraceMeter.startTrace('computeTask', 0); // Enable performance tracing. 73e41f4b71Sopenharmony_ci let timeCost = this.computeTask(totalTimes); 74e41f4b71Sopenharmony_ci this.message = util.format(calculateResult, timeCost.toString()); 75e41f4b71Sopenharmony_ci hiTraceMeter.finishTrace('computeTask', 0); // End performance tracing. 76e41f4b71Sopenharmony_ci this.cancelSuspendDelay(); 77e41f4b71Sopenharmony_ci } 78e41f4b71Sopenharmony_ci 79e41f4b71Sopenharmony_ci build() { 80e41f4b71Sopenharmony_ci Column() { 81e41f4b71Sopenharmony_ci Row(){ 82e41f4b71Sopenharmony_ci Text(this.message) 83e41f4b71Sopenharmony_ci } 84e41f4b71Sopenharmony_ci Row() { 85e41f4b71Sopenharmony_ci Button ('Start Computing') 86e41f4b71Sopenharmony_ci .onClick(this.clickCallback) 87e41f4b71Sopenharmony_ci } 88e41f4b71Sopenharmony_ci .width('100%') 89e41f4b71Sopenharmony_ci .justifyContent(FlexAlign.Center) 90e41f4b71Sopenharmony_ci } 91e41f4b71Sopenharmony_ci .width('100%') 92e41f4b71Sopenharmony_ci .height('100%') 93e41f4b71Sopenharmony_ci .justifyContent(FlexAlign.Center) 94e41f4b71Sopenharmony_ci } 95e41f4b71Sopenharmony_ci} 96e41f4b71Sopenharmony_ci``` 97e41f4b71Sopenharmony_ci 98e41f4b71Sopenharmony_ciTime Profiler in DevEco Studio obtains the following data about the application performance within the duration (less than one minute) from the start of the computing task to switching to the background: 99e41f4b71Sopenharmony_ci 100e41f4b71Sopenharmony_ci**Figure 1** Time Profiler lane of a transient task 101e41f4b71Sopenharmony_ci 102e41f4b71Sopenharmony_ci 103e41f4b71Sopenharmony_ci 104e41f4b71Sopenharmony_ci- ArkTS Callstack: displays the CPU usage and status changes based on the time axis. 105e41f4b71Sopenharmony_ci- User Trace: displays details about user-defined trace tasks triggered in the current period based on the time axis. **H:computeTask** indicates the execution duration of the transient task. 106e41f4b71Sopenharmony_ci- Native Callstack: displays the CPU usage changes, process/thread status, and function call stack based on the timeline. 107e41f4b71Sopenharmony_ci 108e41f4b71Sopenharmony_ciAs shown in the preceding figure, in the period corresponding to **H:computeTask** in the Native Callstack lane, the application process is active and the CPU usage changes in a high range. After the task is canceled, the application is still running, but the process activeness and CPU usage decrease significantly. The system suspends the application several seconds later and reclaims the CPU. 109e41f4b71Sopenharmony_ci 110e41f4b71Sopenharmony_ciThe figures below demonstrate the Native Callstack lane in the task execution phase and in the phase that the task is canceled but the process is not suspended. Check the average CPU usage and maximum CPU usage of the application main thread in the two phases. 111e41f4b71Sopenharmony_ci 112e41f4b71Sopenharmony_ci**Figure 2** CPU usage in the task execution phase 113e41f4b71Sopenharmony_ci 114e41f4b71Sopenharmony_ci 115e41f4b71Sopenharmony_ci 116e41f4b71Sopenharmony_ci**Figure 3** CPU usage when the task is canceled but the process is not suspended 117e41f4b71Sopenharmony_ci 118e41f4b71Sopenharmony_ci 119e41f4b71Sopenharmony_ci 120e41f4b71Sopenharmony_ciIn the first phase, the average CPU usage of the application main thread is 12.6%, and the highest CPU usage is 40.0%. In the second phase, the average CPU usage is 2.2%, and the highest CPU usage is 28.6%. 121e41f4b71Sopenharmony_ci 122e41f4b71Sopenharmony_ciTo sum up, running transient tasks in the background occupies system CPU resources, and too many transient tasks in the background may cause the applications in the foreground to freeze. Therefore, use transient tasks only when necessary, and do not request too many transient tasks at a time. 123e41f4b71Sopenharmony_ci 124e41f4b71Sopenharmony_ciFor details about the constraints on transient tasks, see [Constraints](../task-management/transient-task.md#constraints). 125e41f4b71Sopenharmony_ci 126e41f4b71Sopenharmony_ci## Continuous Task 127e41f4b71Sopenharmony_ci 128e41f4b71Sopenharmony_ciIf an application has a perceivable task that needs to run in an extended period of time in the background, it can request a continuous task to prevent itself from being suspended. Examples of continuous tasks include music playback and navigation in the background. After an application requests a continuous task, the system verifies whether the application is actually executing the continuous task. For details about the development guide, see [Continuous Task](../task-management/continuous-task.md). 129e41f4b71Sopenharmony_ci 130e41f4b71Sopenharmony_ciThe table below lists the types of continuous tasks, which are used in various scenarios. You can select a task type suitable for your case based on the description. 131e41f4b71Sopenharmony_ci 132e41f4b71Sopenharmony_ci| Description | Example Scenario | 133e41f4b71Sopenharmony_ci| ------------------------------ | ------------------------------------ | 134e41f4b71Sopenharmony_ci| Data transfer | The browser downloads a large file in the background.| 135e41f4b71Sopenharmony_ci| Audio and video playback | A music application plays music in the background. | 136e41f4b71Sopenharmony_ci| Audio recording | A recorder records audio in the background. | 137e41f4b71Sopenharmony_ci| Positioning and navigation | A navigation application provides navigation in the background. | 138e41f4b71Sopenharmony_ci| Bluetooth-related task | Transfer a file through Bluetooth. | 139e41f4b71Sopenharmony_ci| Multi-device connection | Carry out distributed service connection. | 140e41f4b71Sopenharmony_ci| WLAN-related task (for system applications only) | Transfer a file over WLAN. | 141e41f4b71Sopenharmony_ci| Voice and video calls (for system applications only)| Use a system chat application to make an audio call in the background. | 142e41f4b71Sopenharmony_ci| Computing task (for specific devices only) | Run antivirus software. | 143e41f4b71Sopenharmony_ci 144e41f4b71Sopenharmony_ci- When an application requests a continuous task of the data transfer type, the system increases the priority of the application process to reduce the probability of terminating the process. However, it still suspends the process. To request a continuous task for file upload or download, the application must call the [upload and download agent API](../reference/apis-basic-services-kit/js-apis-request.md) so that the system functions as the agent. For details, see [Improving File Upload and Download Performance](improve-file-upload-and-download-performance.md/). 145e41f4b71Sopenharmony_ci- To request a continuous task for audio and video playback, the application must use the [AVSession service](../media/avsession/avsession-overview.md) for background playback. 146e41f4b71Sopenharmony_ci- To request a continuous recording task, a dialog box must be displayed dynamically to request user authorization for the microphone permission. 147e41f4b71Sopenharmony_ci 148e41f4b71Sopenharmony_ci### Example 149e41f4b71Sopenharmony_ci 150e41f4b71Sopenharmony_ciThe following simulates a background location scenario. An application subscribes to device location changes and obtains the location every second. To continue the use of the location service after switching to the background, the application requests a continuous task of the location type. The source code is obtained from [Continuous Task Sample](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Performance/PerformanceLibrary/feature/backgroundTask/src/main/ets/view/LongTermTaskView.ets). 151e41f4b71Sopenharmony_ci 152e41f4b71Sopenharmony_ciFirst, declare the continuous task type for the EntryAbility in the **module.json5** file. 153e41f4b71Sopenharmony_ci 154e41f4b71Sopenharmony_ci```javascript 155e41f4b71Sopenharmony_ci{ 156e41f4b71Sopenharmony_ci "module": { 157e41f4b71Sopenharmony_ci ... 158e41f4b71Sopenharmony_ci "abilities": [ 159e41f4b71Sopenharmony_ci { 160e41f4b71Sopenharmony_ci "name": "EntryAbility", 161e41f4b71Sopenharmony_ci ... 162e41f4b71Sopenharmony_ci "backgroundModes": [ 163e41f4b71Sopenharmony_ci "location" 164e41f4b71Sopenharmony_ci ] 165e41f4b71Sopenharmony_ci } 166e41f4b71Sopenharmony_ci ], 167e41f4b71Sopenharmony_ci } 168e41f4b71Sopenharmony_ci} 169e41f4b71Sopenharmony_ci``` 170e41f4b71Sopenharmony_ci 171e41f4b71Sopenharmony_ciThe following permissions are required: 172e41f4b71Sopenharmony_ci 173e41f4b71Sopenharmony_ci- ohos.permission.INTERNET 174e41f4b71Sopenharmony_ci- ohos.permission.LOCATION_IN_BACKGROUND 175e41f4b71Sopenharmony_ci- ohos.permission.APPROXIMATELY_LOCATION 176e41f4b71Sopenharmony_ci- ohos.permission.LOCATION 177e41f4b71Sopenharmony_ci- ohos.permission.KEEP_BACKGROUND_RUNNING 178e41f4b71Sopenharmony_ci 179e41f4b71Sopenharmony_ciFor details about how to request the permissions, see [Declaring Permissions in the Configuration File](../security/AccessToken/declare-permissions-in-acl.md). 180e41f4b71Sopenharmony_ci 181e41f4b71Sopenharmony_ciConfigure the permission in the **module.json5** file. Confirmation from end users is required for the request of some permissions and the toggle of the notification switch. When the system publishes a notification for the continuous task, the notification feature of the application must be enabled. Otherwise, users cannot perceive the continuous task running in the background. 182e41f4b71Sopenharmony_ci 183e41f4b71Sopenharmony_ciThe code for implementing background location is as follows: 184e41f4b71Sopenharmony_ci 185e41f4b71Sopenharmony_ci```javascript 186e41f4b71Sopenharmony_ciimport wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent'; 187e41f4b71Sopenharmony_ciimport common from '@ohos.app.ability.common'; 188e41f4b71Sopenharmony_ciimport backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; 189e41f4b71Sopenharmony_ciimport { BusinessError } from '@ohos.base'; 190e41f4b71Sopenharmony_ciimport geolocation from '@ohos.geoLocationManager'; 191e41f4b71Sopenharmony_ciimport abilityAccessCtrl from '@ohos.abilityAccessCtrl'; 192e41f4b71Sopenharmony_ciimport notificationManager from '@ohos.notificationManager'; 193e41f4b71Sopenharmony_ci 194e41f4b71Sopenharmony_ciconst TAG: string = 'BackgroundLocation'; 195e41f4b71Sopenharmony_ci 196e41f4b71Sopenharmony_ci@Entry 197e41f4b71Sopenharmony_ci@Component 198e41f4b71Sopenharmony_ciexport struct LongTermTaskView { 199e41f4b71Sopenharmony_ci @State latitude: number = 0; 200e41f4b71Sopenharmony_ci @State longitude: number = 0; 201e41f4b71Sopenharmony_ci 202e41f4b71Sopenharmony_ci aboutToAppear() { 203e41f4b71Sopenharmony_ci // Request the permission to send notifications. 204e41f4b71Sopenharmony_ci notificationManager.requestEnableNotification().then(() => { 205e41f4b71Sopenharmony_ci console.info(`[EntryAbility] requestEnableNotification success`); 206e41f4b71Sopenharmony_ci // Request the permission for location. 207e41f4b71Sopenharmony_ci let atManager = abilityAccessCtrl.createAtManager(); 208e41f4b71Sopenharmony_ci try { 209e41f4b71Sopenharmony_ci atManager.requestPermissionsFromUser(getContext(this), ['ohos.permission.INTERNET', 210e41f4b71Sopenharmony_ci 'ohos.permission.LOCATION', 211e41f4b71Sopenharmony_ci 'ohos.permission.LOCATION_IN_BACKGROUND', 212e41f4b71Sopenharmony_ci 'ohos.permission.APPROXIMATELY_LOCATION']) 213e41f4b71Sopenharmony_ci .then((data) => { 214e41f4b71Sopenharmony_ci console.info(`[EntryAbility], data: ${JSON.stringify(data)}`); 215e41f4b71Sopenharmony_ci }) 216e41f4b71Sopenharmony_ci .catch((err: BusinessError) => { 217e41f4b71Sopenharmony_ci console.info(`[EntryAbility], err: ${JSON.stringify(err)}`); 218e41f4b71Sopenharmony_ci }) 219e41f4b71Sopenharmony_ci } catch (err) { 220e41f4b71Sopenharmony_ci console.info(`[EntryAbility], catch err->${JSON.stringify(err)}`); 221e41f4b71Sopenharmony_ci } 222e41f4b71Sopenharmony_ci }).catch((err: BusinessError) => { 223e41f4b71Sopenharmony_ci console.error(`[EntryAbility] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`); 224e41f4b71Sopenharmony_ci }); 225e41f4b71Sopenharmony_ci } 226e41f4b71Sopenharmony_ci 227e41f4b71Sopenharmony_ci // Location change callback. 228e41f4b71Sopenharmony_ci locationChange = async (location: geolocation.Location) => { 229e41f4b71Sopenharmony_ci console.info(TAG, `locationChange location =${JSON.stringify(location)}`); 230e41f4b71Sopenharmony_ci this.latitude = location.latitude; 231e41f4b71Sopenharmony_ci this.longitude = location.longitude; 232e41f4b71Sopenharmony_ci } 233e41f4b71Sopenharmony_ci 234e41f4b71Sopenharmony_ci // Obtain the location. 235e41f4b71Sopenharmony_ci async getLocation() { 236e41f4b71Sopenharmony_ci console.info(TAG, `enter getLocation`); 237e41f4b71Sopenharmony_ci let requestInfo: geolocation.LocationRequest = { 238e41f4b71Sopenharmony_ci priority: geolocation.LocationRequestPriority.FIRST_FIX, // Fast location preferred. 239e41f4b71Sopenharmony_ci scenario: geolocation.LocationRequestScenario.UNSET, // Scenario unspecified. 240e41f4b71Sopenharmony_ci timeInterval: 1, // Time interval at which location information is reported. 241e41f4b71Sopenharmony_ci distanceInterval: 0, // Distance interval at which location information is reported, in meters. 242e41f4b71Sopenharmony_ci maxAccuracy: 100 // Location accuracy. 243e41f4b71Sopenharmony_ci }; 244e41f4b71Sopenharmony_ci console.info(TAG, `on locationChange before`); 245e41f4b71Sopenharmony_ci geolocation.on('locationChange', requestInfo, this.locationChange); 246e41f4b71Sopenharmony_ci console.info(TAG, `on locationChange end`); 247e41f4b71Sopenharmony_ci } 248e41f4b71Sopenharmony_ci 249e41f4b71Sopenharmony_ci // Start the continuous task. 250e41f4b71Sopenharmony_ci startContinuousTask() { 251e41f4b71Sopenharmony_ci let context: Context = getContext(this); 252e41f4b71Sopenharmony_ci // Notification parameters, which are used to specify the target application that is redirected to when the continuous task notification is clicked. 253e41f4b71Sopenharmony_ci let wantAgentInfo: wantAgent.WantAgentInfo = { 254e41f4b71Sopenharmony_ci wants: [ 255e41f4b71Sopenharmony_ci { 256e41f4b71Sopenharmony_ci bundleName: (context as common.UIAbilityContext).abilityInfo.bundleName, 257e41f4b71Sopenharmony_ci abilityName: (context as common.UIAbilityContext).abilityInfo.name 258e41f4b71Sopenharmony_ci } 259e41f4b71Sopenharmony_ci ], 260e41f4b71Sopenharmony_ci operationType: wantAgent.OperationType.START_ABILITY, 261e41f4b71Sopenharmony_ci requestCode: 0, 262e41f4b71Sopenharmony_ci wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 263e41f4b71Sopenharmony_ci }; 264e41f4b71Sopenharmony_ci wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 265e41f4b71Sopenharmony_ci backgroundTaskManager.startBackgroundRunning(context, 266e41f4b71Sopenharmony_ci backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { 267e41f4b71Sopenharmony_ci console.info(`Succeeded in operationing startBackgroundRunning.`); 268e41f4b71Sopenharmony_ci }).catch((err: BusinessError) => { 269e41f4b71Sopenharmony_ci console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 270e41f4b71Sopenharmony_ci }); 271e41f4b71Sopenharmony_ci }); 272e41f4b71Sopenharmony_ci } 273e41f4b71Sopenharmony_ci 274e41f4b71Sopenharmony_ci // Stop the continuous task. 275e41f4b71Sopenharmony_ci stopContinuousTask() { 276e41f4b71Sopenharmony_ci backgroundTaskManager.stopBackgroundRunning(getContext()).then(() => { 277e41f4b71Sopenharmony_ci console.info(`Succeeded in operationing stopBackgroundRunning.`); 278e41f4b71Sopenharmony_ci }).catch((err: BusinessError) => { 279e41f4b71Sopenharmony_ci console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 280e41f4b71Sopenharmony_ci }); 281e41f4b71Sopenharmony_ci } 282e41f4b71Sopenharmony_ci 283e41f4b71Sopenharmony_ci build() { 284e41f4b71Sopenharmony_ci Column() { 285e41f4b71Sopenharmony_ci Column() { 286e41f4b71Sopenharmony_ci Text(this.latitude.toString()) 287e41f4b71Sopenharmony_ci Text(this.longitude.toString()) 288e41f4b71Sopenharmony_ci } 289e41f4b71Sopenharmony_ci .width('100%') 290e41f4b71Sopenharmony_ci 291e41f4b71Sopenharmony_ci Column() { 292e41f4b71Sopenharmony_ci Button('Enable Locating') 293e41f4b71Sopenharmony_ci .onClick(() => { 294e41f4b71Sopenharmony_ci this.startContinuousTask(); 295e41f4b71Sopenharmony_ci this.getLocation(); 296e41f4b71Sopenharmony_ci }) 297e41f4b71Sopenharmony_ci Button('Disable Locating') 298e41f4b71Sopenharmony_ci .onClick(async () => { 299e41f4b71Sopenharmony_ci await geolocation.off('locationChange'); 300e41f4b71Sopenharmony_ci this.stopContinuousTask(); 301e41f4b71Sopenharmony_ci }) 302e41f4b71Sopenharmony_ci .margin({ top: 10 }) 303e41f4b71Sopenharmony_ci } 304e41f4b71Sopenharmony_ci .width('100%') 305e41f4b71Sopenharmony_ci } 306e41f4b71Sopenharmony_ci .width('100%') 307e41f4b71Sopenharmony_ci .height('100%') 308e41f4b71Sopenharmony_ci .justifyContent(FlexAlign.Center) 309e41f4b71Sopenharmony_ci } 310e41f4b71Sopenharmony_ci} 311e41f4b71Sopenharmony_ci``` 312e41f4b71Sopenharmony_ci 313e41f4b71Sopenharmony_ciBased on this scenario, the power consumption test tool obtains the following data about the device power consumption within 30 minutes. 314e41f4b71Sopenharmony_ci 315e41f4b71Sopenharmony_ci| Task | Test Duration (s)| Normalized Current (mA)| Maximum Current (mA)| Normalized Power Consumption (mAH)| 316e41f4b71Sopenharmony_ci| -------------------- | ----------- | ------------ | ------------ | ------------- | 317e41f4b71Sopenharmony_ci| Locating task in the background| 1836.4 | 15.52 | 995.72 | 7.92 | 318e41f4b71Sopenharmony_ci| No background task | 1839.9 | 0.85 | 404.03 | 0.44 | 319e41f4b71Sopenharmony_ci 320e41f4b71Sopenharmony_ci- Normalized current: average current when the voltage is 3.8 V. 321e41f4b71Sopenharmony_ci- Formula for calculating the normalized power consumption: Normalized current x Test duration/3600, where 3600 is the number of seconds in an hour. 322e41f4b71Sopenharmony_ci 323e41f4b71Sopenharmony_ciThe test data shows that the device power consumption increases significantly within 30 minutes when the locating task keeps running in the background. 324e41f4b71Sopenharmony_ci 325e41f4b71Sopenharmony_ciDo not use too many continuous tasks from the perspective of power consumption. If continuous tasks must be used, you can optimize the task execution process to minimize the power consumption. The following provides some optimization suggestions: 326e41f4b71Sopenharmony_ci 327e41f4b71Sopenharmony_ci- In scenarios that do not have high requirements on locating, increase the reporting time interval and distance interval to reduce the update frequency. 328e41f4b71Sopenharmony_ci 329e41f4b71Sopenharmony_ci- Reduce the number of network requests and the network request interval as much as possible. 330e41f4b71Sopenharmony_ci 331e41f4b71Sopenharmony_ci- Use efficient data formats and parsing methods during data transmission to reduce task execution time. 332e41f4b71Sopenharmony_ci 333e41f4b71Sopenharmony_ciFor details about the constraints on continuous tasks, see [Constraints](../task-management/continuous-task.md). 334e41f4b71Sopenharmony_ci 335e41f4b71Sopenharmony_ci## Deferred Task 336e41f4b71Sopenharmony_ci 337e41f4b71Sopenharmony_ciIf an application needs to execute a non-real-time task after switching to the background, the application can request a deferred task. When the specified conditions (including the network type, charging type, storage status, battery status, and timing status) are met, the system adds the task to the execution queue. Then the system starts the application to execute the task based on the memory, power consumption, device temperature, and user habits. 338e41f4b71Sopenharmony_ci 339e41f4b71Sopenharmony_ciDeferred tasks apply to scenarios such as software updates, information collection, and data processing. For details about the development guide, see [Deferred Task](../task-management/work-scheduler.md). 340e41f4b71Sopenharmony_ci 341e41f4b71Sopenharmony_ci## Agent-powered Reminder 342e41f4b71Sopenharmony_ci 343e41f4b71Sopenharmony_ciAfter an application switches to the background or an application process is terminated, it may have scheduled tasks for reminding users, for example, flash sale reminders for shopping applications. To meet this requirement, the system provides agent-powered reminders (implemented by **reminderAgentManager**). When the application switches to the background or the process is terminated, the system sends reminders on behalf of the application. For details about the development guide, see [Agent-powered Reminder](../task-management/agent-powered-reminder.md). 344e41f4b71Sopenharmony_ci 345e41f4b71Sopenharmony_ciCurrently, the following reminder types are supported: 346e41f4b71Sopenharmony_ci 347e41f4b71Sopenharmony_ci- Countdown timers: Applications can use this type to implement short-time timing notification services, for example, flash sale reminders. 348e41f4b71Sopenharmony_ci- Calendar events: Applications can use this type to implement long-time notification services, for example, birthday reminders. 349e41f4b71Sopenharmony_ci- Alarm clocks: Applications can use this type to implement alarm-related services, for example, wake-up alarms. 350e41f4b71Sopenharmony_ci 351e41f4b71Sopenharmony_ci## Summary 352e41f4b71Sopenharmony_ci 353e41f4b71Sopenharmony_ciProper selection and use of background tasks are important for optimizing user experience and reducing performance consumption. The table below describes these background tasks from different dimensions. 354e41f4b71Sopenharmony_ci 355e41f4b71Sopenharmony_ci| Task Type| Task Description | Background Application Status | Example Scenario | 356e41f4b71Sopenharmony_ci| -------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | 357e41f4b71Sopenharmony_ci| No background | The application does not execute any task in the background. | The application is suspended within several seconds after switching to the background. | General | 358e41f4b71Sopenharmony_ci| Transient task| Suitable for tasks that have high requirements on real-time performance and can be completed in a short period of time. | Within the one-off quota, the application is not suspended until the task is canceled. If the task is not canceled when the one-off quota expires, the application process is terminated. | Small file download, caching, and information sending | 359e41f4b71Sopenharmony_ci| Continuous task| Suitable for perceivable task that needs to run in an extended period of time in the background. | The application is not suspended until the task is canceled. If the task is not canceled, the application process is terminated when the task is complete. | Data transfer, audio playback, recording, positioning and navigation, Bluetooth-related task, WLAN-related task, multi-device connection, voice and video calls, and computing tasks| 360e41f4b71Sopenharmony_ci| Deferred task| Suitable for tasks that do not have high requirements on real-time performance and can be executed at a later time.| The system enqueues tasks and schedules them in a unified manner based on the memory and power consumption. The application is suspended after switching to the background. When the preset conditions are met, the system starts the application and creates an Extension process to execute the task. The maximum execution duration for a single callback is 2 minutes. If the task is not canceled when the maximum duration expires, the system terminates the Extension process.| Software update, information collection, and data processing | 361e41f4b71Sopenharmony_ci| Agent-powered reminder| The system sends reminders on behalf of the application. | The application is suspended or the process is terminated. When the conditions are met, the system sends reminders on behalf of the application. | Alarm clocks, countdown timer, and calendar events | 362