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