1# @ohos.backgroundTaskManager (后台任务管理)
2
3本模块提供后台任务管理能力。
4
5当应用或业务模块处于后台(无可见界面)时,如果有需要继续执行或者后续执行的业务,可基于业务类型,申请短时任务延迟挂起(Suspend)或者长时任务避免进入挂起状态。
6
7应用有不可中断且短时间能完成的任务时(如,用户在文件管理器上点击垃圾文件清理,若清理未完成时退到后台,文件管理器需要申请短时任务完成清理),可以使用短时任务机制。
8
9应用中存在用户能够直观感受到的且需要一直在后台运行的业务时(如,后台播放音乐),可以使用长时任务机制。
10
11
12>  **说明:**
13>
14> - 从API Version 9 开始,该接口不再维护,推荐使用新接口[@ohos.resourceschedule.backgroundTaskManager (后台任务管理)](js-apis-resourceschedule-backgroundTaskManager.md)。
15>
16> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
17
18
19## 导入模块
20
21```ts
22import backgroundTaskManager from '@ohos.backgroundTaskManager';
23```
24
25
26## backgroundTaskManager.requestSuspendDelay
27
28requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo
29
30后台应用申请延迟挂起。
31
32延迟挂起时间一般情况下默认值为3分钟,低电量(依据系统低电量广播)时默认值为1分钟。
33
34**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
35
36**参数**:
37
38| 参数名      | 类型                   | 必填   | 说明                             |
39| -------- | -------------------- | ---- | ------------------------------ |
40| reason   | string               | 是    | 延迟挂起申请的原因。                     |
41| callback | Callback<void> | 是    | 延迟即将超时的回调函数,一般在超时前6秒通过此回调通知应用。 |
42
43**返回值**:
44
45| 类型                                    | 说明        |
46| ------------------------------------- | --------- |
47| [DelaySuspendInfo](#delaysuspendinfo) | 返回延迟挂起信息。 |
48
49**示例**:
50
51  ```ts
52  import backgroundTaskManager from '@ohos.backgroundTaskManager';
53  import { BusinessError } from '@ohos.base';
54
55  // 设置延迟任务挂起的原因
56  let myReason = 'test requestSuspendDelay';
57  // 申请延迟任务
58  let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
59      console.info("Request suspension delay will time out.");
60  })
61  // 打印延迟任务信息
62  let id = delayInfo.requestId;
63  let time = delayInfo.actualDelayTime;
64  console.info("The requestId is: " + id);
65  console.info("The actualDelayTime is: " + time);
66  ```
67
68
69## backgroundTaskManager.getRemainingDelayTime
70
71getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void
72
73获取应用程序进入挂起状态前的剩余时间,使用callback形式返回。
74
75**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
76
77**参数**:
78
79| 参数名       | 类型                          | 必填   | 说明                                       |
80| --------- | --------------------------- | ---- | ---------------------------------------- |
81| requestId | number                      | 是    | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 |
82| callback  | AsyncCallback<number> | 是    | 指定的callback回调方法。用于返回应用程序进入挂起状态之前的剩余时间,以毫秒为单位。 |
83
84**示例**:
85
86  ```ts
87  import backgroundTaskManager from '@ohos.backgroundTaskManager';
88  import { BusinessError } from '@ohos.base';
89
90  let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {});
91  backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId, (err: BusinessError, res: number) => {
92      if(err) {
93          console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.code);
94      } else {
95          console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
96      }
97  })
98  ```
99
100
101## backgroundTaskManager.getRemainingDelayTime
102
103getRemainingDelayTime(requestId: number): Promise<number>
104
105获取应用程序进入挂起状态前的剩余时间,使用Promise形式返回。
106
107**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
108
109**参数**:
110
111| 参数名       | 类型     | 必填   | 说明         |
112| --------- | ------ | ---- | ---------- |
113| requestId | number | 是    | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 |
114
115**返回值**:
116
117| 类型                    | 说明                                       |
118| --------------------- | ---------------------------------------- |
119| Promise<number> | 指定的Promise回调方法。返回应用程序进入挂起状态之前的剩余时间,以毫秒为单位。 |
120
121**示例**:
122
123```ts
124import backgroundTaskManager from '@ohos.backgroundTaskManager';
125import { BusinessError } from '@ohos.base';
126
127let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {});
128    backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then((res:number) => {
129    console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
130}).catch((err : BusinessError) => {
131    console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code);
132})
133```
134
135
136## backgroundTaskManager.cancelSuspendDelay
137
138cancelSuspendDelay(requestId: number): void
139
140取消延迟挂起。
141
142**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
143
144**参数**:
145
146| 参数名       | 类型     | 必填   | 说明         |
147| --------- | ------ | ---- | ---------- |
148| requestId | number | 是    | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 |
149
150**示例**:
151
152  ```ts
153  let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {});
154  backgroundTaskManager.cancelSuspendDelay(delayInfo.requestId);
155  ```
156
157
158## backgroundTaskManager.startBackgroundRunning<sup>8+</sup>
159
160startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback&lt;void&gt;): void
161
162向系统申请长时任务,使用callback形式返回结果。
163
164**需要权限:** ohos.permission.KEEP_BACKGROUND_RUNNING
165
166**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
167
168**参数**:
169
170| 参数名    | 类型                                          | 必填 | 说明                                                         |
171| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
172| context   | Context                                       | 是   | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](../apis-ability-kit/js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](../apis-ability-kit/js-apis-inner-application-context.md)。 |
173| bgMode    | [BackgroundMode](#backgroundmode8)            | 是   | 向系统申请的后台模式。                                       |
174| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | 是   | 通知参数,用于指定长时任务通知点击后跳转的界面。             |
175| callback  | AsyncCallback&lt;void&gt;                     | 是   | callback形式返回启动长时任务的结果。                         |
176
177**示例**:
178
179FA模型示例:
180
181```js
182import backgroundTaskManager from '@ohos.backgroundTaskManager';
183import featureAbility from '@ohos.ability.featureAbility';
184import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent';
185import { BusinessError } from '@ohos.base';
186
187function callback(err: BusinessError, data: void) {
188  if (err) {
189    console.error("Operation startBackgroundRunning failed Cause: " + err);
190  } else {
191    console.info("Operation startBackgroundRunning succeeded");
192  }
193}
194
195let wantAgentInfo : wantAgent.WantAgentInfo = {
196  wants: [
197    {
198      bundleName: "com.example.myapplication",
199      abilityName: "EntryAbility"
200    }
201  ],
202  operationType: wantAgent.OperationType.START_ABILITY,
203  requestCode: 0,
204  wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
205};
206
207wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => {
208  backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
209    backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
210});
211
212```
213
214Stage模型示例:
215
216```ts
217import UIAbility from '@ohos.app.ability.UIAbility';
218import backgroundTaskManager from '@ohos.backgroundTaskManager';
219import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent';
220import Want from '@ohos.app.ability.Want';
221import AbilityConstant from '@ohos.app.ability.AbilityConstant';
222import { BusinessError } from '@ohos.base';
223
224function callback(err: BusinessError, data: void) {
225  if (err) {
226    console.error("Operation startBackgroundRunning failed Cause: " + err);
227  } else {
228    console.info("Operation startBackgroundRunning succeeded");
229  }
230}
231
232export default class EntryAbility extends UIAbility {
233  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
234    let wantAgentInfo : wantAgent.WantAgentInfo = {
235      wants: [
236        {
237          bundleName: "com.example.myapplication",
238          abilityName: "EntryAbility"
239        }
240      ],
241      operationType: wantAgent.OperationType.START_ABILITY,
242      requestCode: 0,
243      wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
244    };
245
246    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => {
247      backgroundTaskManager.startBackgroundRunning(this.context,
248        backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback)
249    });
250  }
251};
252```
253
254## backgroundTaskManager.startBackgroundRunning<sup>8+</sup>
255
256startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt;
257
258向系统申请长时任务,使用promise形式返回结果。
259
260**需要权限:** ohos.permission.KEEP_BACKGROUND_RUNNING
261
262**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
263
264**参数**:
265
266| 参数名    | 类型                                          | 必填 | 说明                                                         |
267| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
268| context   | Context                                       | 是   | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](../apis-ability-kit/js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](../apis-ability-kit/js-apis-inner-application-context.md)。 |
269| bgMode    | [BackgroundMode](#backgroundmode8)            | 是   | 向系统申请的后台模式。                                       |
270| wantAgent | [WantAgent](../apis-ability-kit/js-apis-app-ability-wantAgent.md) | 是   | 通知参数,用于指定长时任务通知点击跳转的界面。               |
271
272**返回值**:
273
274| 类型             | 说明               |
275| -------------- | ---------------- |
276| Promise\<void> | 使用Promise形式返回结果。 |
277
278**示例**:
279
280FA模型示例(需使用js代码开发):
281
282```js
283import backgroundTaskManager from '@ohos.backgroundTaskManager';
284import featureAbility from '@ohos.ability.featureAbility';
285import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent';
286import { BusinessError } from '@ohos.base';
287
288let wantAgentInfo : wantAgent.WantAgentInfo = {
289  wants: [
290    {
291      bundleName: "com.example.myapplication",
292      abilityName: "EntryAbility"
293    }
294  ],
295  operationType: wantAgent.OperationType.START_ABILITY,
296  requestCode: 0,
297  wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
298};
299
300wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
301  backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
302    backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
303    console.info("Operation startBackgroundRunning succeeded");
304  }).catch((err: BusinessError) => {
305    console.error("Operation startBackgroundRunning failed Cause: " + err);
306  });
307});
308```
309
310Stage模型示例:
311
312```ts
313import UIAbility from '@ohos.app.ability.UIAbility';
314import backgroundTaskManager from '@ohos.backgroundTaskManager';
315import wantAgent, { WantAgent } from '@ohos.app.ability.wantAgent';
316import Want from '@ohos.app.ability.Want';
317import AbilityConstant from '@ohos.app.ability.AbilityConstant';
318import { BusinessError } from '@ohos.base';
319
320export default class EntryAbility extends UIAbility {
321  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
322    let wantAgentInfo : wantAgent.WantAgentInfo = {
323      wants: [
324        {
325          bundleName: "com.example.myapplication",
326          abilityName: "EntryAbility"
327        }
328      ],
329      // 点击通知后,动作类型
330      operationType: wantAgent.OperationType.START_ABILITY,
331      requestCode: 0,
332      // 点击通知后,动作执行属性
333      wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
334    };
335
336    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => {
337      backgroundTaskManager.startBackgroundRunning(this.context,
338        backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => {
339        console.info("Operation startBackgroundRunning succeeded");
340      }).catch((err: BusinessError) => {
341        console.error("Operation startBackgroundRunning failed Cause: " + err);
342      });
343    });
344  }
345};
346```
347
348## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup>
349
350stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void
351
352向系统申请取消长时任务,使用callback形式返回结果。
353
354**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
355
356**参数**:
357
358| 参数名      | 类型                        | 必填   | 说明                                       |
359| -------- | ------------------------- | ---- | ---------------------------------------- |
360| context  | Context                   | 是    | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](../apis-ability-kit/js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](../apis-ability-kit/js-apis-inner-application-context.md)。 |
361| callback | AsyncCallback&lt;void&gt; | 是    | callback形式返回启动长时任务的结果。                   |
362
363**示例**:
364
365FA模型示例(需使用js代码开发):
366
367```js
368import backgroundTaskManager from '@ohos.backgroundTaskManager';
369import featureAbility from '@ohos.ability.featureAbility';
370import { BusinessError } from '@ohos.base';
371
372function callback(err: BusinessError, data: void) {
373  if (err) {
374    console.error("Operation stopBackgroundRunning failed Cause: " + err);
375  } else {
376    console.info("Operation stopBackgroundRunning succeeded");
377  }
378}
379
380backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback);
381
382```
383
384Stage模型示例:
385
386```ts
387import UIAbility from '@ohos.app.ability.UIAbility';
388import backgroundTaskManager from '@ohos.backgroundTaskManager';
389import Want from '@ohos.app.ability.Want';
390import AbilityConstant from '@ohos.app.ability.AbilityConstant';
391import { BusinessError } from '@ohos.base';
392
393function callback(err: BusinessError, data: void) {
394  if (err) {
395    console.error("Operation stopBackgroundRunning failed Cause: " + err);
396  } else {
397    console.info("Operation stopBackgroundRunning succeeded");
398  }
399}
400
401export default class EntryAbility extends UIAbility {
402  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
403    backgroundTaskManager.stopBackgroundRunning(this.context, callback);
404  }
405};
406```
407
408## backgroundTaskManager.stopBackgroundRunning<sup>8+</sup>
409
410stopBackgroundRunning(context: Context): Promise&lt;void&gt;
411
412向系统申请取消长时任务,使用promise形式返回结果。
413
414**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
415
416**参数**:
417
418| 参数名     | 类型      | 必填   | 说明                                       |
419| ------- | ------- | ---- | ---------------------------------------- |
420| context | Context | 是    | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](../apis-ability-kit/js-apis-inner-app-context.md)。<br>Stage模型的应用Context定义见[Context](../apis-ability-kit/js-apis-inner-application-context.md)。 |
421
422**返回值**:
423
424| 类型             | 说明               |
425| -------------- | ---------------- |
426| Promise\<void> | 使用Promise形式返回结果。 |
427
428**示例**:
429
430FA模型示例:
431
432```js
433import backgroundTaskManager from '@ohos.backgroundTaskManager';
434import featureAbility from '@ohos.ability.featureAbility';
435import { BusinessError } from '@ohos.base';
436
437// 取消长时任务
438backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
439  console.info("Operation stopBackgroundRunning succeeded");
440}).catch((err: BusinessError) => {
441  console.error("Operation stopBackgroundRunning failed Cause: " + err);
442});
443
444```
445
446Stage模型示例:
447
448```ts
449import UIAbility from '@ohos.app.ability.UIAbility';
450import backgroundTaskManager from '@ohos.backgroundTaskManager';
451import Want from '@ohos.app.ability.Want';
452import AbilityConstant from '@ohos.app.ability.AbilityConstant';
453import { BusinessError } from '@ohos.base';
454
455export default class EntryAbility extends UIAbility {
456  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
457    // 取消长时任务
458    backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
459      console.info("Operation stopBackgroundRunning succeeded");
460    }).catch((err: BusinessError) => {
461      console.error("Operation stopBackgroundRunning failed Cause: " + err);
462    });
463  }
464};
465```
466
467## DelaySuspendInfo
468
469延迟挂起信息。
470
471**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
472
473| 名称             | 类型     | 必填   | 说明                                       |
474| --------------- | ------ | ---- | ---------------------------------------- |
475| requestId       | number | 是    | 延迟挂起的请求ID。                               |
476| actualDelayTime | number | 是    | 应用的实际挂起延迟时间,以毫秒为单位。<br/>一般情况下默认值为180000,低电量(依据系统低电量广播)时默认值为60000。 |
477
478
479## BackgroundMode<sup>8+</sup>
480
481**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
482
483| 名称                     | 值  | 说明                    |
484| ----------------------- | ---- | --------------------- |
485| DATA_TRANSFER           | 1    | 数据传输。                  |
486| AUDIO_PLAYBACK          | 2    | 音频播放。                  |
487| AUDIO_RECORDING         | 3    | 录音。                    |
488| LOCATION                | 4    | 定位导航。                  |
489| BLUETOOTH_INTERACTION   | 5    | 蓝牙相关。                  |
490| MULTI_DEVICE_CONNECTION | 6    | 多设备互联。                 |
491| TASK_KEEPING            | 9    | 计算任务(仅在特定设备生效)。        |
492