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