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