1# 长时任务(ArkTS) 2 3## 概述 4 5### 功能介绍 6 7应用退至后台后,在后台需要长时间运行用户可感知的任务,如播放音乐、导航等。为防止应用进程被挂起,导致对应功能异常,可以申请长时任务,使应用在后台长时间运行。在长时任务中,支持同时申请多种类型的任务,也可以对任务类型进行更新。应用退至后台执行业务时,系统会做一致性校验,确保应用在执行相应的长时任务。应用在申请长时任务成功后,通知栏会显示与长时任务相关联的消息,用户删除通知栏消息时,系统会自动停止长时任务。 8 9### 使用场景 10 11下表给出了当前长时任务支持的类型,包含数据传输、音视频播放、录制、定位导航、蓝牙相关业务、多设备互联、<!--Del-->WLAN相关业务、<!--DelEnd-->音视频通话和计算任务。可以参考下表中的场景举例,选择合适的长时任务类型。 12 13**表1** 长时任务类型 14| 参数名 | 描述 | 配置项 | 场景举例 | 15| -------- | -------- | -------- | -------- | 16| DATA_TRANSFER | 数据传输 | dataTransfer | 非托管形式的上传、下载,如在浏览器后台上传或下载数据。 | 17| AUDIO_PLAYBACK | 音视频播放 | audioPlayback | 音频、视频在后台播放,音视频投播。 <br> **说明:** 支持在原子化服务中使用。| 18| AUDIO_RECORDING | 录制 | audioRecording | 录音、录屏退后台。 | 19| LOCATION | 定位导航 | location | 定位、导航。 | 20| BLUETOOTH_INTERACTION | 蓝牙相关业务 | bluetoothInteraction | 通过蓝牙传输文件时退后台。 | 21| MULTI_DEVICE_CONNECTION | 多设备互联 | multiDeviceConnection | 分布式业务连接、投播。<br> **说明:** 支持在原子化服务中使用。 | 22| <!--DelRow-->WIFI_INTERACTION | WLAN相关业务(仅对系统应用开放) | wifiInteraction | 通过WLAN传输文件时退后台。 | 23| VOIP<sup>13+</sup> | 音视频通话 | voip | 某些聊天类应用(具有音视频业务)音频、视频通话时退后台。| 24| TASK_KEEPING | 计算任务(仅对2in1设备开放) | taskKeeping | 如杀毒软件。 | 25 26关于DATA_TRANSFER(数据传输)说明: 27 28- 在数据传输时,若应用使用[上传下载代理接口](../reference/apis-basic-services-kit/js-apis-request.md)托管给系统,即使申请DATA_TRANSFER的后台任务,应用退后台时还是会被挂起。 29 30- 在数据传输时,应用需要更新进度。如果进度长时间(超过10分钟)不更新,数据传输的长时任务会被取消。更新进度实现可参考[startBackgroundRunning()](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning12)中的示例。 31 32关于AUDIO_PLAYBACK(音视频播放)说明: 33 34- 若要通过AUDIO_PLAYBACK实现后台播放,须使用媒体会话服务([AVSession](../media/avsession/avsession-overview.md))进行音视频开发。 35 36- 音视频投播,是指将一台设备的音视频投至另一台设备播放。投播退至后台,长时任务会检测音视频播放和投屏两个业务,只要有其一正常运行,长时任务就不会终止。 37 38### 约束与限制 39 40**申请限制**:Stage模型中,长时任务仅支持UIAbility申请;FA模型中,长时任务仅支持ServiceAbility申请。长时任务支持设备当前应用申请,也支持跨设备或跨应用申请,跨设备或跨应用仅对系统应用开放。 41 42**数量限制**:一个UIAbility(FA模型则为ServiceAbility)同一时刻仅支持申请一个长时任务,即在一个长时任务结束后才可能继续申请。如果一个应用同时需要申请多个长时任务,需要创建多个UIAbility;一个应用的一个UIAbility申请长时任务后,整个应用下的所有进程均不会被挂起。 43 44**运行限制**: 45 46- 申请长时任务后,应用未执行相应的业务,系统会对应用进行管控。如系统检测到应用申请了AUDIO_PLAYBACK(音视频播放),但实际未播放音乐,长时任务会被取消。 47 48- 申请长时任务后,应用执行的业务类型与申请的不一致,系统会对应用进行管控。如系统检测到应用只申请了AUDIO_PLAYBACK(音视频播放),但实际上除了播放音乐(对应AUDIO_PLAYBACK类型),还在进行录制(对应AUDIO_RECORDING类型)。 49 50- 申请长时任务后,应用的业务已执行完,系统会对应用进行管控。 51 52- 若运行长时任务的进程后台负载持续高于所申请类型的典型负载,系统会对应用进行管控。 53 54> **说明:** 55> 56> 应用按需求申请长时任务,当应用无需在后台运行(任务结束)时,要及时主动取消长时任务,否则系统会强行取消。例如用户主动点击音乐暂停播放时,应用需及时取消对应的长时任务;用户再次点击音乐播放时,需重新申请长时任务。 57> 58> 若音频在后台播放时被[打断](../media/audio/audio-playback-concurrency.md),系统会自行检测和停止长时任务,音频重启播放时,需要再次申请长时任务。 59> 60> 后台播放音频的应用,在后台停止长时任务的同时,需要暂停或停止音频流,否则应用会被系统强制终止。 61 62## 接口说明 63 64**表2** 主要接口 65 66以下是长时任务开发使用的相关接口,下表均以Promise形式为例,更多接口及使用方式请见[后台任务管理](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager.md)。 67 68| 接口名 | 描述 | 69| -------- | -------- | 70| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: [WantAgent](../reference/apis-ability-kit/js-apis-app-ability-wantAgent.md)): Promise<void> | 申请长时任务 | 71| stopBackgroundRunning(context: Context): Promise<void> | 取消长时任务 | 72 73## 开发步骤 74 75本文以申请录制长时任务为例,实现如下功能: 76 77- 点击“申请长时任务”按钮,应用申请录制长时任务成功,通知栏显示“正在运行录制任务”通知。 78 79- 点击“取消长时任务”按钮,取消长时任务,通知栏撤销相关通知。 80 81### Stage模型 82 831. 需要申请ohos.permission.KEEP_BACKGROUND_RUNNING权限,配置方式请参见[声明权限](../security/AccessToken/declare-permissions.md)。 84 852. 声明后台模式类型。在module.json5文件中为需要使用长时任务的UIAbility声明相应的长时任务类型,配置文件中填写长时任务类型的[配置项](continuous-task.md#使用场景)。 86 87 ```json 88 "module": { 89 "abilities": [ 90 { 91 "backgroundModes": [ 92 // 长时任务类型的配置项 93 "audioRecording" 94 ] 95 } 96 ], 97 // ... 98 } 99 ``` 100 1013. 导入模块。 102 103 长时任务相关的模块为@ohos.resourceschedule.backgroundTaskManager和@ohos.app.ability.wantAgent,其余模块按实际需要导入。 104 105 ```ts 106 import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 107 import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 108 import { window } from '@kit.ArkUI'; 109 import { rpc } from '@kit.IPCKit' 110 import { BusinessError } from '@kit.BasicServicesKit'; 111 import { wantAgent, WantAgent } from '@kit.AbilityKit'; 112 ``` 113 1144. 申请和取消长时任务。 115 116 **设备当前应用**申请长时任务示例代码如下: 117 118 ```ts 119 @Entry 120 @Component 121 struct Index { 122 @State message: string = 'ContinuousTask'; 123 // 通过getContext方法,来获取page所在的UIAbility上下文。 124 private context: Context = getContext(this); 125 126 startContinuousTask() { 127 let wantAgentInfo: wantAgent.WantAgentInfo = { 128 // 点击通知后,将要执行的动作列表 129 // 添加需要被拉起应用的bundleName和abilityName 130 wants: [ 131 { 132 bundleName: "com.example.myapplication", 133 abilityName: "MainAbility" 134 } 135 ], 136 // 指定点击通知栏消息后的动作是拉起ability 137 actionType: wantAgent.OperationType.START_ABILITY, 138 // 使用者自定义的一个私有值 139 requestCode: 0, 140 // 点击通知后,动作执行属性 141 actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 142 }; 143 144 try { 145 // 通过wantAgent模块下getWantAgent方法获取WantAgent对象 146 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 147 try { 148 let list: Array<string> = ["audioRecording"]; 149 backgroundTaskManager.startBackgroundRunning(this.context, list, wantAgentObj).then((res: backgroundTaskManager.ContinuousTaskNotification) => { 150 console.info("Operation startBackgroundRunning succeeded"); 151 // 此处执行具体的长时任务逻辑,如录音,录制等。 152 }).catch((error: BusinessError) => { 153 console.error(`Failed to Operation startBackgroundRunning. code is ${error.code} message is ${error.message}`); 154 }); 155 } catch (error) { 156 console.error(`Failed to Operation startBackgroundRunning. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 157 } 158 }); 159 } catch (error) { 160 console.error(`Failed to Operation getWantAgent. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 161 } 162 } 163 164 stopContinuousTask() { 165 backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { 166 console.info(`Succeeded in operationing stopBackgroundRunning.`); 167 }).catch((err: BusinessError) => { 168 console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 169 }); 170 } 171 172 build() { 173 Row() { 174 Column() { 175 Text("Index") 176 .fontSize(50) 177 .fontWeight(FontWeight.Bold) 178 179 Button() { 180 Text('申请长时任务').fontSize(25).fontWeight(FontWeight.Bold) 181 } 182 .type(ButtonType.Capsule) 183 .margin({ top: 10 }) 184 .backgroundColor('#0D9FFB') 185 .width(250) 186 .height(40) 187 .onClick(() => { 188 // 通过按钮申请长时任务 189 this.startContinuousTask(); 190 }) 191 192 Button() { 193 Text('取消长时任务').fontSize(25).fontWeight(FontWeight.Bold) 194 } 195 .type(ButtonType.Capsule) 196 .margin({ top: 10 }) 197 .backgroundColor('#0D9FFB') 198 .width(250) 199 .height(40) 200 .onClick(() => { 201 // 此处结束具体的长时任务的执行 202 203 // 通过按钮取消长时任务 204 this.stopContinuousTask(); 205 }) 206 } 207 .width('100%') 208 } 209 .height('100%') 210 } 211 } 212 ``` 213 <!--Del--> 214 215 **跨设备或跨应用**申请长时任务示例代码如下。跨设备或跨应用在后台执行长时任务时,可以通过Call的方式在后台创建并运行UIAbility,具体使用请参考[Call调用开发指南(同设备)](../application-models/uiability-intra-device-interaction.md#通过call调用实现uiability交互仅对系统应用开放)和[Call调用开发指南(跨设备)](../application-models/hop-multi-device-collaboration.md#通过跨设备call调用实现多端协同)。 216 217 ```ts 218 const MSG_SEND_METHOD: string = 'CallSendMsg' 219 220 let mContext: Context; 221 222 function startContinuousTask() { 223 let wantAgentInfo : wantAgent.WantAgentInfo = { 224 // 点击通知后,将要执行的动作列表 225 wants: [ 226 { 227 bundleName: "com.example.myapplication", 228 abilityName: "com.example.myapplication.MainAbility", 229 } 230 ], 231 // 点击通知后,动作类型 232 actionType: wantAgent.OperationType.START_ABILITY, 233 // 使用者自定义的一个私有值 234 requestCode: 0, 235 // 点击通知后,动作执行属性 236 actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 237 }; 238 239 // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 240 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { 241 backgroundTaskManager.startBackgroundRunning(mContext, 242 backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { 243 console.info(`Succeeded in operationing startBackgroundRunning.`); 244 }).catch((err: BusinessError) => { 245 console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 246 }); 247 }); 248 } 249 250 function stopContinuousTask() { 251 backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { 252 console.info(`Succeeded in operationing stopBackgroundRunning.`); 253 }).catch((err: BusinessError) => { 254 console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 255 }); 256 } 257 258 class MyParcelable implements rpc.Parcelable { 259 num: number = 0; 260 str: string = ''; 261 262 constructor(num: number, string: string) { 263 this.num = num; 264 this.str = string; 265 } 266 267 marshalling(messageSequence: rpc.MessageSequence) { 268 messageSequence.writeInt(this.num); 269 messageSequence.writeString(this.str); 270 return true; 271 } 272 273 unmarshalling(messageSequence: rpc.MessageSequence) { 274 this.num = messageSequence.readInt(); 275 this.str = messageSequence.readString(); 276 return true; 277 } 278 } 279 280 function sendMsgCallback(data: rpc.MessageSequence) { 281 console.info('BgTaskAbility funcCallBack is called ' + data); 282 let receivedData: MyParcelable = new MyParcelable(0, ''); 283 data.readParcelable(receivedData); 284 console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); 285 // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 286 if (receivedData.str === 'start_bgtask') { 287 // 申请长时 288 startContinuousTask(); 289 } else if (receivedData.str === 'stop_bgtask') { 290 // 取消长时 291 stopContinuousTask(); 292 } 293 return new MyParcelable(10, 'Callee test'); 294 } 295 296 export default class BgTaskAbility extends UIAbility { 297 // Ability创建 298 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 299 console.info("[Demo] BgTaskAbility onCreate"); 300 try { 301 this.callee.on(MSG_SEND_METHOD, sendMsgCallback) 302 } catch (error) { 303 console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); 304 } 305 mContext = this.context; 306 } 307 308 // Ability销毁 309 onDestroy() { 310 console.info('[Demo] BgTaskAbility onDestroy'); 311 } 312 313 onWindowStageCreate(windowStage: window.WindowStage) { 314 console.info('[Demo] BgTaskAbility onWindowStageCreate'); 315 316 windowStage.loadContent('pages/Index', (error, data) => { 317 if (error.code) { 318 console.error(`load content failed with error ${JSON.stringify(error)}`); 319 return; 320 } 321 console.info(`load content succeed with data ${JSON.stringify(data)}`); 322 }); 323 } 324 325 onWindowStageDestroy() { 326 console.info('[Demo] BgTaskAbility onWindowStageDestroy'); 327 } 328 329 onForeground() { 330 console.info('[Demo] BgTaskAbility onForeground'); 331 } 332 333 onBackground() { 334 console.info('[Demo] BgTaskAbility onBackground'); 335 } 336 }; 337 ``` 338 339 <!--DelEnd--> 340 341<!--Del--> 342### FA模型 343 3441. 启动并连接ServiceAbility。 345 346 - 不需要与用户进行交互时,采用startAbility()方法启动ServiceAbility(具体使用请参考[ServiceAbility组件](../application-models/serviceability-overview.md),并在ServiceAbility的onStart回调方法中,调用长时任务的申请和取消接口。 347 348 - 需要与用户进行交互时(如播放音乐),采用connectAbility()方法启动并连接ServiceAbility(具体使用请参考[ServiceAbility组件](../application-models/serviceability-overview.md),在获取到服务的代理对象后,与服务进行通信,控制长时任务的申请和取消。 349 3502. 配置权限和声明后台模式类型。 351 352 在config.json文件中配置长时任务权限ohos.permission.KEEP_BACKGROUND_RUNNING,配置方式请参见[声明权限](../security/AccessToken/declare-permissions.md)。同时,为需要使用长时任务的ServiceAbility声明相应的长时任务类型。 353 354 ```json 355 "module": { 356 "package": "com.example.myapplication", 357 "abilities": [ 358 { 359 "backgroundModes": [ 360 "audioRecording", 361 ], // 后台模式类型 362 "type": "service" // ability类型为service 363 } 364 ], 365 "reqPermissions": [ 366 { 367 "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 368 } 369 ] 370 } 371 ``` 372 3733. 导入模块。 374 375 ```js 376 import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 377 import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 378 import { window } from '@kit.ArkUI'; 379 import { rpc } from '@kit.IPCKit' 380 import { BusinessError } from '@kit.BasicServicesKit'; 381 import { wantAgent, WantAgent } from '@kit.AbilityKit'; 382 ``` 383 3844. 申请和取消长时任务。在 ServiceAbility 中,调用 [startBackgroundRunning](#接口说明) 接口和 [stopBackgroundRunning](#接口说明) 接口实现长时任务的申请和取消,通过js代码实现。 385 386 ```js 387 function startContinuousTask() { 388 let wantAgentInfo: wantAgent.WantAgentInfo = { 389 // 点击通知后,将要执行的动作列表 390 wants: [ 391 { 392 bundleName: "com.example.myapplication", 393 abilityName: "com.example.myapplication.MainAbility" 394 } 395 ], 396 // 点击通知后,动作类型 397 actionType: wantAgent.OperationType.START_ABILITY, 398 // 使用者自定义的一个私有值 399 requestCode: 0, 400 // 点击通知后,动作执行属性 401 actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 402 }; 403 404 // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 405 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 406 backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), 407 backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { 408 console.info(`Succeeded in operationing startBackgroundRunning.`); 409 }).catch((err: BusinessError) => { 410 console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 411 }); 412 }); 413 } 414 415 function stopContinuousTask() { 416 backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { 417 console.info(`Succeeded in operationing stopBackgroundRunning.`); 418 }).catch((err: BusinessError) => { 419 console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 420 }); 421 } 422 423 async function processAsyncJobs() { 424 // 此处执行具体的长时任务。 425 426 // 长时任务执行完,调用取消接口,释放资源。 427 stopContinuousTask(); 428 } 429 430 let mMyStub: MyStub; 431 432 // 采用connectAbility的方式启动服务 433 class MyStub extends rpc.RemoteObject { 434 constructor(des: string) { 435 super(des); 436 } 437 438 onRemoteRequest(code: number, data: rpc.MessageParcel, reply: rpc.MessageParcel, option: rpc.MessageOption) { 439 console.log('ServiceAbility onRemoteRequest called'); 440 // code 的具体含义用户自定义 441 if (code === 1) { 442 // 接收到申请长时任务的请求码 443 startContinuousTask(); 444 // 此处执行具体长时任务 445 } else if (code === 2) { 446 // 接收到取消长时任务的请求码 447 stopContinuousTask(); 448 } else { 449 console.log('ServiceAbility unknown request code'); 450 } 451 return true; 452 } 453 } 454 455 // 采用startAbility的方式启动服务 456 class ServiceAbility { 457 onStart(want: Want) { 458 console.info('ServiceAbility onStart'); 459 mMyStub = new MyStub("ServiceAbility-test"); 460 // 在执行长时任务前,调用申请接口。 461 startContinuousTask(); 462 processAsyncJobs(); 463 } 464 465 onStop() { 466 console.info('ServiceAbility onStop'); 467 } 468 469 onConnect(want: Want) { 470 console.info('ServiceAbility onConnect'); 471 return mMyStub; 472 } 473 474 onReconnect(want: Want) { 475 console.info('ServiceAbility onReconnect'); 476 } 477 478 onDisconnect() { 479 console.info('ServiceAbility onDisconnect'); 480 } 481 482 onCommand(want: Want, startId: number) { 483 console.info('ServiceAbility onCommand'); 484 } 485 } 486 487 export default new ServiceAbility(); 488 ``` 489<!--DelEnd--> 490 491## 相关实例 492 493针对长时任务开发,有以下相关实例可供参考: 494 495- [长时任务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/ContinuousTask)