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