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. 声明后台模式类型。 86 在module.json5文件中为需要使用长时任务的UIAbility声明相应的长时任务类型,配置文件中填写长时任务类型的[配置项](continuous-task.md#使用场景)。 87 88 ```json 89 "module": { 90 "abilities": [ 91 { 92 "backgroundModes": [ 93 // 长时任务类型的配置项 94 "audioRecording" 95 ] 96 } 97 ], 98 // ... 99 } 100 ``` 101 1023. 导入模块。 103 104 长时任务相关的模块为@ohos.resourceschedule.backgroundTaskManager和@ohos.app.ability.wantAgent,其余模块按实际需要导入。 105 106 ```ts 107 import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 108 import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 109 import { window } from '@kit.ArkUI'; 110 import { rpc } from '@kit.IPCKit' 111 import { BusinessError } from '@kit.BasicServicesKit'; 112 import { wantAgent, WantAgent } from '@kit.AbilityKit'; 113 ``` 114 1154. 申请和取消长时任务。 116 117 **设备当前应用**申请长时任务示例代码如下: 118 119 ```ts 120 function callback(info: backgroundTaskManager.ContinuousTaskCancelInfo) { 121 // 长时任务id 122 console.info('OnContinuousTaskCancel callback id ' + info.id); 123 // 长时任务取消原因 124 console.info('OnContinuousTaskCancel callback reason ' + info.reason); 125 } 126 127 @Entry 128 @Component 129 struct Index { 130 @State message: string = 'ContinuousTask'; 131 // 通过getUIContext().getHostContet()方法,来获取page所在的UIAbility上下文 132 private context: Context | undefined = this.getUIContext().getHostContet(); 133 134 OnContinuousTaskCancel() { 135 try { 136 backgroundTaskManager.on("continuousTaskCancel", callback); 137 console.info(`Succeeded in operationing OnContinuousTaskCancel.`); 138 } catch (error) { 139 console.error(`Operation OnContinuousTaskCancel failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 140 } 141 } 142 143 OffContinuousTaskCancel() { 144 try { 145 // callback参数不传,则取消所有已注册的回调 146 backgroundTaskManager.off("continuousTaskCancel", callback); 147 console.info(`Succeeded in operationing OffContinuousTaskCancel.`); 148 } catch (error) { 149 console.error(`Operation OffContinuousTaskCancel failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 150 } 151 } 152 153 startContinuousTask() { 154 let wantAgentInfo: wantAgent.WantAgentInfo = { 155 // 点击通知后,将要执行的动作列表 156 // 添加需要被拉起应用的bundleName和abilityName 157 wants: [ 158 { 159 bundleName: "com.example.myapplication", 160 abilityName: "MainAbility" 161 } 162 ], 163 // 指定点击通知栏消息后的动作是拉起ability 164 actionType: wantAgent.OperationType.START_ABILITY, 165 // 使用者自定义的一个私有值 166 requestCode: 0, 167 // 点击通知后,动作执行属性 168 actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], 169 // 车钥匙长时任务子类型。只有申请bluetoothInteraction类型的长时任务,车钥匙子类型才能生效。 170 // 确保extraInfo参数中的Key值为backgroundTaskManager.BackgroundModeType.SUB_MODE,否则子类型不生效。 171 // extraInfo: { [backgroundTaskManager.BackgroundModeType.SUB_MODE] : backgroundTaskManager.BackgroundSubMode.CAR_KEY } 172 }; 173 174 try { 175 // 通过wantAgent模块下getWantAgent方法获取WantAgent对象 176 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 177 try { 178 let list: Array<string> = ["audioRecording"]; 179 // let list: Array<string> = ["bluetoothInteraction"]; 长时任务类型包含bluetoothInteraction,CAR_KEY子类型合法 180 backgroundTaskManager.startBackgroundRunning(this.context, list, wantAgentObj).then((res: backgroundTaskManager.ContinuousTaskNotification) => { 181 console.info("Operation startBackgroundRunning succeeded"); 182 // 此处执行具体的长时任务逻辑,如录音,录制等。 183 }).catch((error: BusinessError) => { 184 console.error(`Failed to Operation startBackgroundRunning. code is ${error.code} message is ${error.message}`); 185 }); 186 } catch (error) { 187 console.error(`Failed to Operation startBackgroundRunning. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 188 } 189 }); 190 } catch (error) { 191 console.error(`Failed to Operation getWantAgent. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`); 192 } 193 } 194 195 196 stopContinuousTask() { 197 backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { 198 console.info(`Succeeded in operationing stopBackgroundRunning.`); 199 }).catch((err: BusinessError) => { 200 console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 201 }); 202 } 203 204 build() { 205 Row() { 206 Column() { 207 Text("Index") 208 .fontSize(50) 209 .fontWeight(FontWeight.Bold) 210 211 Button() { 212 Text('申请长时任务').fontSize(25).fontWeight(FontWeight.Bold) 213 } 214 .type(ButtonType.Capsule) 215 .margin({ top: 10 }) 216 .backgroundColor('#0D9FFB') 217 .width(250) 218 .height(40) 219 .onClick(() => { 220 // 通过按钮申请长时任务 221 this.startContinuousTask(); 222 }) 223 224 Button() { 225 Text('取消长时任务').fontSize(25).fontWeight(FontWeight.Bold) 226 } 227 .type(ButtonType.Capsule) 228 .margin({ top: 10 }) 229 .backgroundColor('#0D9FFB') 230 .width(250) 231 .height(40) 232 .onClick(() => { 233 // 此处结束具体的长时任务的执行 234 235 // 通过按钮取消长时任务 236 this.stopContinuousTask(); 237 }) 238 239 Button() { 240 Text('注册长时任务取消回调').fontSize(25).fontWeight(FontWeight.Bold) 241 } 242 .type(ButtonType.Capsule) 243 .margin({ top: 10 }) 244 .backgroundColor('#0D9FFB') 245 .width(250) 246 .height(40) 247 .onClick(() => { 248 // 通过按钮注册长时任务取消回调 249 this.OnContinuousTaskCancel(); 250 }) 251 252 Button() { 253 Text('取消注册长时任务取消回调').fontSize(25).fontWeight(FontWeight.Bold) 254 } 255 .type(ButtonType.Capsule) 256 .margin({ top: 10 }) 257 .backgroundColor('#0D9FFB') 258 .width(250) 259 .height(40) 260 .onClick(() => { 261 // 通过按钮取消注册长时任务取消回调 262 this.OffContinuousTaskCancel(); 263 }) 264 } 265 .width('100%') 266 } 267 .height('100%') 268 } 269 } 270 ``` 271 <!--Del--> 272 273 **跨设备或跨应用**申请长时任务示例代码如下。跨设备或跨应用在后台执行长时任务时,可以通过Call的方式在后台创建并运行UIAbility,具体使用请参考[Call调用开发指南(同设备)](../application-models/uiability-intra-device-interaction.md#通过call调用实现uiability交互仅对系统应用开放)和[Call调用开发指南(跨设备)](../application-models/hop-multi-device-collaboration.md#通过跨设备call调用实现多端协同)。 274 275 ```ts 276 const MSG_SEND_METHOD: string = 'CallSendMsg' 277 278 let mContext: Context; 279 280 function startContinuousTask() { 281 let wantAgentInfo : wantAgent.WantAgentInfo = { 282 // 点击通知后,将要执行的动作列表 283 wants: [ 284 { 285 bundleName: "com.example.myapplication", 286 abilityName: "com.example.myapplication.MainAbility", 287 } 288 ], 289 // 点击通知后,动作类型 290 actionType: wantAgent.OperationType.START_ABILITY, 291 // 使用者自定义的一个私有值 292 requestCode: 0, 293 // 点击通知后,动作执行属性 294 actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 295 }; 296 297 // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 298 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => { 299 backgroundTaskManager.startBackgroundRunning(mContext, 300 backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { 301 console.info(`Succeeded in operationing startBackgroundRunning.`); 302 }).catch((err: BusinessError) => { 303 console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 304 }); 305 }); 306 } 307 308 function stopContinuousTask() { 309 backgroundTaskManager.stopBackgroundRunning(mContext).then(() => { 310 console.info(`Succeeded in operationing stopBackgroundRunning.`); 311 }).catch((err: BusinessError) => { 312 console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 313 }); 314 } 315 316 class MyParcelable implements rpc.Parcelable { 317 num: number = 0; 318 str: string = ''; 319 320 constructor(num: number, string: string) { 321 this.num = num; 322 this.str = string; 323 } 324 325 marshalling(messageSequence: rpc.MessageSequence) { 326 messageSequence.writeInt(this.num); 327 messageSequence.writeString(this.str); 328 return true; 329 } 330 331 unmarshalling(messageSequence: rpc.MessageSequence) { 332 this.num = messageSequence.readInt(); 333 this.str = messageSequence.readString(); 334 return true; 335 } 336 } 337 338 function sendMsgCallback(data: rpc.MessageSequence) { 339 console.info('BgTaskAbility funcCallBack is called ' + data); 340 let receivedData: MyParcelable = new MyParcelable(0, ''); 341 data.readParcelable(receivedData); 342 console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); 343 // 可以根据Caller端发送的序列化数据的str值,执行不同的方法。 344 if (receivedData.str === 'start_bgtask') { 345 // 申请长时 346 startContinuousTask(); 347 } else if (receivedData.str === 'stop_bgtask') { 348 // 取消长时 349 stopContinuousTask(); 350 } 351 return new MyParcelable(10, 'Callee test'); 352 } 353 354 export default class BgTaskAbility extends UIAbility { 355 // Ability创建 356 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 357 console.info("[Demo] BgTaskAbility onCreate"); 358 try { 359 this.callee.on(MSG_SEND_METHOD, sendMsgCallback) 360 } catch (error) { 361 console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`); 362 } 363 mContext = this.context; 364 } 365 366 // Ability销毁 367 onDestroy() { 368 console.info('[Demo] BgTaskAbility onDestroy'); 369 } 370 371 onWindowStageCreate(windowStage: window.WindowStage) { 372 console.info('[Demo] BgTaskAbility onWindowStageCreate'); 373 374 windowStage.loadContent('pages/Index', (error, data) => { 375 if (error.code) { 376 console.error(`load content failed with error ${JSON.stringify(error)}`); 377 return; 378 } 379 console.info(`load content succeed with data ${JSON.stringify(data)}`); 380 }); 381 } 382 383 onWindowStageDestroy() { 384 console.info('[Demo] BgTaskAbility onWindowStageDestroy'); 385 } 386 387 onForeground() { 388 console.info('[Demo] BgTaskAbility onForeground'); 389 } 390 391 onBackground() { 392 console.info('[Demo] BgTaskAbility onBackground'); 393 } 394 }; 395 ``` 396 397 <!--DelEnd--> 398 399<!--Del--> 400### FA模型 401 4021. 启动并连接ServiceAbility。 403 404 - 不需要与用户进行交互时,采用startAbility()方法启动ServiceAbility(具体使用请参考[ServiceAbility组件](../application-models/serviceability-overview.md),并在ServiceAbility的onStart回调方法中,调用长时任务的申请和取消接口。 405 406 - 需要与用户进行交互时(如播放音乐),采用connectAbility()方法启动并连接ServiceAbility(具体使用请参考[ServiceAbility组件](../application-models/serviceability-overview.md),在获取到服务的代理对象后,与服务进行通信,控制长时任务的申请和取消。 407 4082. 配置权限和声明后台模式类型。 409 410 在config.json文件中配置长时任务权限ohos.permission.KEEP_BACKGROUND_RUNNING,配置方式请参见[声明权限](../security/AccessToken/declare-permissions.md)。同时,为需要使用长时任务的ServiceAbility声明相应的长时任务类型。 411 412 ```json 413 "module": { 414 "package": "com.example.myapplication", 415 "abilities": [ 416 { 417 "backgroundModes": [ 418 "audioRecording", 419 ], // 后台模式类型 420 "type": "service" // ability类型为service 421 } 422 ], 423 "reqPermissions": [ 424 { 425 "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // 长时任务权限 426 } 427 ] 428 } 429 ``` 430 4313. 导入模块。 432 433 ```js 434 import { backgroundTaskManager } from '@kit.BackgroundTasksKit'; 435 import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; 436 import { window } from '@kit.ArkUI'; 437 import { rpc } from '@kit.IPCKit' 438 import { BusinessError } from '@kit.BasicServicesKit'; 439 import { wantAgent, WantAgent } from '@kit.AbilityKit'; 440 ``` 441 4424. 申请和取消长时任务。在 ServiceAbility 中,调用 [startBackgroundRunning](#接口说明) 接口和 [stopBackgroundRunning](#接口说明) 接口实现长时任务的申请和取消,通过js代码实现。 443 444 ```js 445 function startContinuousTask() { 446 let wantAgentInfo: wantAgent.WantAgentInfo = { 447 // 点击通知后,将要执行的动作列表 448 wants: [ 449 { 450 bundleName: "com.example.myapplication", 451 abilityName: "com.example.myapplication.MainAbility" 452 } 453 ], 454 // 点击通知后,动作类型 455 actionType: wantAgent.OperationType.START_ABILITY, 456 // 使用者自定义的一个私有值 457 requestCode: 0, 458 // 点击通知后,动作执行属性 459 actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] 460 }; 461 462 // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 463 wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => { 464 backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), 465 backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => { 466 console.info(`Succeeded in operationing startBackgroundRunning.`); 467 }).catch((err: BusinessError) => { 468 console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 469 }); 470 }); 471 } 472 473 function stopContinuousTask() { 474 backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { 475 console.info(`Succeeded in operationing stopBackgroundRunning.`); 476 }).catch((err: BusinessError) => { 477 console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`); 478 }); 479 } 480 481 async function processAsyncJobs() { 482 // 此处执行具体的长时任务。 483 484 // 长时任务执行完,调用取消接口,释放资源。 485 stopContinuousTask(); 486 } 487 488 let mMyStub: MyStub; 489 490 // 采用connectAbility的方式启动服务 491 class MyStub extends rpc.RemoteObject { 492 constructor(des: string) { 493 super(des); 494 } 495 496 onRemoteRequest(code: number, data: rpc.MessageParcel, reply: rpc.MessageParcel, option: rpc.MessageOption) { 497 console.log('ServiceAbility onRemoteRequest called'); 498 // code 的具体含义用户自定义 499 if (code === 1) { 500 // 接收到申请长时任务的请求码 501 startContinuousTask(); 502 // 此处执行具体长时任务 503 } else if (code === 2) { 504 // 接收到取消长时任务的请求码 505 stopContinuousTask(); 506 } else { 507 console.log('ServiceAbility unknown request code'); 508 } 509 return true; 510 } 511 } 512 513 // 采用startAbility的方式启动服务 514 class ServiceAbility { 515 onStart(want: Want) { 516 console.info('ServiceAbility onStart'); 517 mMyStub = new MyStub("ServiceAbility-test"); 518 // 在执行长时任务前,调用申请接口。 519 startContinuousTask(); 520 processAsyncJobs(); 521 } 522 523 onStop() { 524 console.info('ServiceAbility onStop'); 525 } 526 527 onConnect(want: Want) { 528 console.info('ServiceAbility onConnect'); 529 return mMyStub; 530 } 531 532 onReconnect(want: Want) { 533 console.info('ServiceAbility onReconnect'); 534 } 535 536 onDisconnect() { 537 console.info('ServiceAbility onDisconnect'); 538 } 539 540 onCommand(want: Want, startId: number) { 541 console.info('ServiceAbility onCommand'); 542 } 543 } 544 545 export default new ServiceAbility(); 546 ``` 547<!--DelEnd--> 548 549## 相关实例 550 551针对长时任务开发,有以下相关实例可供参考: 552 553- [长时任务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/ContinuousTask)