1# Background Task Management Development 2 3## When to Use 4 5If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type. 6 7## Transient Tasks 8 9### Available APIs 10 11**Table 1** Main APIs for transient tasks 12 13| API| Description| 14| -------- | -------- | 15| requestSuspendDelay(reason: string, callback: Callback<void>): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.<br>The default duration value of delayed suspension is 180000 milliseconds when the battery level is normal and 60000 milliseconds when the battery level is low. | 16| getRemainingDelayTime(requestId: number): Promise<number> | Obtains the remaining duration before the application is suspended.<br>This API uses a promise to return the task execution result.| 17| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay.| 18 19 20### How to Develop 21 22 231. Request a suspension delay. 24 25 ```js 26 import backgroundTaskManager from '@ohos.backgroundTaskManager'; 27 28 let myReason = 'test requestSuspendDelay'; 29 let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { 30 console.info("Request suspension delay will time out."); 31 }); 32 33 var id = delayInfo.requestId; 34 console.info("requestId is: " + id); 35 ``` 36 37 382. Obtain the remaining duration before the application is suspended. 39 40 ```js 41 backgroundTaskManager.getRemainingDelayTime(id).then( res => { 42 console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); 43 }).catch( err => { 44 console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); 45 }); 46 ``` 47 48 493. Cancel the suspension delay. 50 51 ```js 52 backgroundTaskManager.cancelSuspendDelay(id); 53 ``` 54 55 56### Development Examples 57 58```js 59import backgroundTaskManager from '@ohos.backgroundTaskManager'; 60let myReason = 'test requestSuspendDelay'; 61 62// Request a suspension delay. 63let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { 64 console.info("Request suspension delay will time out."); 65}); 66 67// Print the suspension delay information. 68var id = delayInfo.requestId; 69var time = delayInfo.actualDelayTime; 70console.info("The requestId is: " + id); 71console.info("The actualDelayTime is: " + time); 72 73// Obtain the remaining duration before the application is suspended. 74backgroundTaskManager.getRemainingDelayTime(id).then( res => { 75 console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); 76}).catch( err => { 77 console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); 78}); 79 80// Cancel the suspension delay. 81backgroundTaskManager.cancelSuspendDelay(id); 82``` 83 84## Continuous Tasks 85 86### Required Permissions 87 88ohos.permission.KEEP_BACKGROUND_RUNNING 89 90### Available APIs 91 92**Table 2** Main APIs for continuous tasks 93 94| API| Description| 95| -------- | -------- | 96| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> | Requests a continuous task from the system so that the application keeps running in the background.| 97| stopBackgroundRunning(context: Context): Promise<void> | Cancels the continuous task.| 98 99 100For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantAgent.md). 101 102**Table 3** Background modes 103 104| Name| ID| Description| Item| 105| -------- | -------- | -------- | -------- | 106| DATA_TRANSFER | 1 | Data transfer.| dataTransfer | 107| AUDIO_PLAYBACK | 2 | Audio playback.| audioPlayback | 108| AUDIO_RECORDING | 3 | Audio recording.| audioRecording | 109| LOCATION | 4 | Positioning and navigation.| location | 110| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task.| bluetoothInteraction | 111| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection.| multiDeviceConnection | 112| WIFI_INTERACTION | 7 | WLAN-related task (reserved).| wifiInteraction | 113| VOIP | 8 | Voice and video call (reserved).| voip | 114| TASK_KEEPING | 9 | Computing task (for specific devices only).| taskKeeping | 115 116 117### How to Develop 118 1191. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission and background mode type in the **config.json** file, with the ability type set to **service**. 120 121 ``` 122 "module": { 123 "package": "com.example.myapplication", 124 "abilities": [ 125 { 126 "backgroundModes": [ 127 "dataTransfer", 128 "location" 129 ], // Background mode 130 "type": "service" // The ability type is service. 131 } 132 ], 133 "reqPermissions": [ 134 { 135 "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission 136 } 137 ] 138 } 139 ``` 140 1412. Request a continuous task. 142 143 ```js 144 import backgroundTaskManager from '@ohos.backgroundTaskManager'; 145 import featureAbility from '@ohos.ability.featureAbility'; 146 import wantAgent from '@ohos.wantAgent'; 147 148 let wantAgentInfo = { 149 wants: [ 150 { 151 bundleName: "com.example.myapplication", 152 abilityName: "com.example.myapplication.MainAbility" 153 } 154 ], 155 operationType: wantAgent.OperationType.START_ABILITY, 156 requestCode: 0, 157 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 158 }; 159 160 // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. 161 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { 162 backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), 163 backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { 164 console.info("Operation startBackgroundRunning succeeded"); 165 }).catch((err) => { 166 console.error("Operation startBackgroundRunning failed Cause: " + err); 167 }); 168 }); 169 ``` 170 1713. Cancel the continuous task. 172 173 ```js 174 import backgroundTaskManager from '@ohos.backgroundTaskManager'; 175 import featureAbility from '@ohos.ability.featureAbility'; 176 177 backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { 178 console.info("Operation stopBackgroundRunning succeeded"); 179 }).catch((err) => { 180 console.error("Operation stopBackgroundRunning failed Cause: " + err); 181 }); 182 183 ``` 184 185### Development Examples 186For details about how to use the Service ability in the FA model, see [Service Ability Development](../ability/fa-serviceability.md). 187 188If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources. 189 190If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks. 191 192```js 193import backgroundTaskManager from '@ohos.backgroundTaskManager'; 194import featureAbility from '@ohos.ability.featureAbility'; 195import wantAgent from '@ohos.wantAgent'; 196import rpc from "@ohos.rpc"; 197 198function startBackgroundRunning() { 199 let wantAgentInfo = { 200 // List of operations to be executed after the notification is clicked. 201 wants: [ 202 { 203 bundleName: "com.example.myapplication", 204 abilityName: "com.example.myapplication.MainAbility" 205 } 206 ], 207 // Type of the operation to perform after the notification is clicked. 208 operationType: wantAgent.OperationType.START_ABILITY, 209 // Custom request code. 210 requestCode: 0, 211 // Execution attribute of the operation to perform after the notification is clicked. 212 wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 213 }; 214 215 // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module. 216 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { 217 backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), 218 backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { 219 console.info("Operation startBackgroundRunning succeeded"); 220 }).catch((err) => { 221 console.error("Operation startBackgroundRunning failed Cause: " + err); 222 }); 223 }); 224} 225 226function stopBackgroundRunning() { 227 backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { 228 console.info("Operation stopBackgroundRunning succeeded"); 229 }).catch((err) => { 230 console.error("Operation stopBackgroundRunning failed Cause: " + err); 231 }); 232} 233 234let mMyStub; 235 236class MyStub extends rpc.RemoteObject { 237 constructor(des) { 238 if (typeof des === 'string') { 239 super(des); 240 } else { 241 return null; 242 } 243 } 244 onRemoteRequest(code, data, reply, option) { 245 console.log('ServiceAbility onRemoteRequest called'); 246 // The meaning of code is user-defined. 247 if (code === 1) { 248 // Received the request code for requesting a continuous task. 249 startContinuousTask(); 250 // Execute the continuous task. 251 } else if (code === 2) { 252 // Received the request code for canceling the continuous task. 253 stopContinuousTask(); 254 } else { 255 console.log('ServiceAbility unknown request code'); 256 } 257 return true; 258 } 259} 260 261export default { 262 onStart(want) { 263 console.info('ServiceAbility onStart'); 264 mMyStub = new MyStub("ServiceAbility-test"); 265 startBackgroundRunning(); 266 // Execute a specific continuous task in the background. 267 stopBackgroundRunning(); 268 }, 269 onStop() { 270 console.info('ServiceAbility onStop'); 271 }, 272 onConnect(want) { 273 console.info('ServiceAbility onConnect'); 274 return mMyStub; 275 }, 276 onReconnect(want) { 277 console.info('ServiceAbility onReconnect'); 278 }, 279 onDisconnect() { 280 console.info('ServiceAbility onDisconnect'); 281 }, 282 onCommand(want, restart, startId) { 283 console.info('ServiceAbility onCommand'); 284 } 285}; 286``` 287