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