• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Continuous Task (ArkTS)
2
3## Overview
4
5### Introduction
6
7If an application has a perceivable task that needs to run in an extended period of time in the background, it can request a continuous task to prevent itself from being suspended. Examples of continuous tasks include music playback and navigation in the background. Within a continuous task, the application can concurrently request multiple types of tasks and update the task types. When the application operates in the background, the system performs consistency check to ensure that the application is executing the corresponding continuous task. Upon successful request for a continuous task, the notification panel displays the message associated with the task. If the user deletes the message, the system automatically terminates the task.
8
9### Use Cases
10
11The table below lists the types of continuous tasks, which are used in various scenarios. You can select a task type suitable for your case based on the description.
12
13**Table 1** Continuous task types
14| Name| Description| Item| Example Scenario|
15| -------- | -------- | -------- | -------- |
16| DATA_TRANSFER | Data transfer| dataTransfer | Non-hosting uploading and downloading operations, like those occurring in the background of a web browser for data transfer.|
17| AUDIO_PLAYBACK | Audio and video playback| audioPlayback | Audio and video playback in the background; audio and video casting.<br> **NOTE**<br>It can be used in atomic services.|
18| AUDIO_RECORDING | Audio recording| audioRecording | Recording and screen capture in the background.|
19| LOCATION | Positioning and navigation| location | Positioning and navigation.|
20| BLUETOOTH_INTERACTION | Bluetooth-related services| bluetoothInteraction | An application transitions into the background during the process of file transfer using Bluetooth.|
21| MULTI_DEVICE_CONNECTION | Multi-device connection| multiDeviceConnection | Distributed service connection and casting.<br> **NOTE**<br>It can be used in atomic services.|
22| <!--DelRow-->WIFI_INTERACTION | WLAN-related services (for system applications only)| wifiInteraction  | An application transitions into the background during the process of file transfer using WLAN.|
23| VOIP<sup>13+</sup> | Audio and video calls| voip  | Chat applications (with audio and video services) transition into the background during audio and video calls.|
24| TASK_KEEPING | Computing task (for 2-in-1 devices only).| taskKeeping  | Antivirus software is running.|
25
26Description of **DATA_TRANSFER**:
27
28- During data transfer, if an application uses the [upload and download agent API](../reference/apis-basic-services-kit/js-apis-request.md) to hand over tasks to the system, the application will be suspended in the background even if it has requested the continuous task of the DATA_TRANSFER type.
29
30- During data transfer, the application needs to update the progress. If the progress is not updated for more than 10 minutes, the continuous task of the DATA_TRANSFER type will be canceled. For details about how to update the progress, see the example in [startBackgroundRunning()](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning12).
31
32Description of **AUDIO_PLAYBACK**:
33
34- To implement background playback through **AUDIO_PLAYBACK**, you must use the [AVSession](../media/avsession/avsession-overview.md) for audio and video development.
35
36- Casting audio and video involves transmitting content from one device to another for playback purposes. If the application transitions to the background while casting, the continuous task checks the audio and video playback and casting services. The task will persist as long as either the audio and video playback or casting service is running properly.
37
38### Constraints
39
40**Ability restrictions**: In the stage model, only the UIAbility can request continuous tasks. In the FA model, only the ServiceAbility can request continuous tasks. Continuous tasks can be requested by the current application on the current device or across devices or by other applications. However, the capability to make cross-device or cross-application requests is restricted to system applications.
41
42**Quantity restrictions**: A UIAbility (ServiceAbility in the FA model) can request only one continuous task at a time. If a UIAbility has a running continuous task, it can request another one only after the running task is finished. If an application needs to request multiple continuous tasks at the same time, it must create multiple UIAbilities. After a UIAbility requests a continuous task, all the processes of the application are not suspended.
43
44**Running restrictions**:
45
46- If an application requests a continuous task but does not carry out the relevant service, the system imposes restrictions on the application. For example, if the system detects that an application has requested a continuous task of the AUDIO_PLAYBACK type but does not play audio, the system cancels the continuous task.
47
48- If an application requests a continuous task but carries out a service that does not match the requested type, the system imposes restrictions on the application. For example, if the system detects that an application requests a continuous task of the AUDIO_PLAYBACK type, but the application is playing audio (corresponding to the AUDIO_PLAYBACK type) and recording (corresponding to the AUDIO_RECORDING type), the system enforces management measures.
49
50- When an application's operations are completed after a continuous task request, the system imposes restrictions on the application.
51
52- If the background load of the process that runs a continuous task is higher than the corresponding typical load for a long period of time, the system performs certain control.
53
54> **NOTE**
55>
56> The application shall proactively cancel a continuous task when it is finished. Otherwise, the system will forcibly cancel the task. For example, when a user taps the UI to pause music playback, the application must cancel the continuous task in a timely manner. When the user taps the UI again to continue music playback, the application needs to request a continuous task.
57>
58> If an application that plays an audio in the background is [interrupted](../media/audio/audio-playback-concurrency.md), the system automatically detects and stops the continuous task. The application must request a continuous task again to restart the playback.
59>
60> When an application that plays audio in the background stops a continuous task, it must suspend or stop the audio stream. Otherwise, the application will be forcibly terminated by the system.
61
62## Available APIs
63
64**Table 2** Main APIs for continuous tasks
65
66The table below uses promise as an example to describe the APIs used for developing continuous tasks. For details about more APIs and their usage, see [Background Task Management](../reference/apis-backgroundtasks-kit/js-apis-resourceschedule-backgroundTaskManager.md).
67
68| API| Description|
69| -------- | -------- |
70| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: [WantAgent](../reference/apis-ability-kit/js-apis-app-ability-wantAgent.md)): Promise&lt;void&gt; | Requests a continuous task.|
71| stopBackgroundRunning(context: Context): Promise&lt;void&gt; | Cancels a continuous task.|
72
73## How to Develop
74
75The following walks you through how to request a continuous task for recording to implement the following functions:
76
77- When a user touches **Request Continuous Task**, the application requests a continuous task for recording, and a message is displayed in the notification bar, indicating that a recording task is running.
78
79- When a user touches **Cancel Continuous Task**, the application cancels the continuous task, and the notification message is removed.
80
81### Stage Model
82
831. Declare the **ohos.permission.KEEP_BACKGROUND_RUNNING** permission. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md).
84
852. Declare the continuous task type.
86   Declare the type of the continuous task for the target UIAbility in the **module.json5** file. Set the corresponding [configuration item](continuous-task.md#use-cases) in the configuration file.
87
88   ```json
89    "module": {
90        "abilities": [
91            {
92                "backgroundModes": [
93                 // Configuration item of the continuous task type
94                "audioRecording"
95                ]
96            }
97        ],
98        // ...
99    }
100   ```
101
1023. Import the modules.
103
104   Import the modules related to continuous tasks: @ohos.resourceschedule.backgroundTaskManager and @ohos.app.ability.wantAgent. Import other modules based on the project requirements.
105
106   ```ts
107    import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
108    import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
109    import { window } from '@kit.ArkUI';
110    import { rpc } from '@kit.IPCKit'
111    import { BusinessError } from '@kit.BasicServicesKit';
112    import { wantAgent, WantAgent } from '@kit.AbilityKit';
113   ```
114
1154. Request and cancel a continuous task.
116
117   The code snippet below shows how an application requests a continuous task for itself.
118
119   ```ts
120    function callback(info: backgroundTaskManager.ContinuousTaskCancelInfo) {
121      // ID of a continuous task.
122      console.info('OnContinuousTaskCancel callback id ' + info.id);
123      // Reason for canceling the continuous task.
124      console.info('OnContinuousTaskCancel callback reason ' + info.reason);
125    }
126
127    @Entry
128    @Component
129    struct Index {
130      @State message: string = 'ContinuousTask';
131     // Use getContext to obtain the context of the UIAbility for the page.
132      private context: Context = getContext(this);
133
134      OnContinuousTaskCancel() {
135        try {
136           backgroundTaskManager.on("continuousTaskCancel", callback);
137           console.info(`Succeeded in operationing OnContinuousTaskCancel.`);
138        } catch (error) {
139           console.error(`Operation OnContinuousTaskCancel failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
140        }
141      }
142
143      OffContinuousTaskCancel() {
144        try {
145           // If the callback parameter is not passed, all callbacks associated with the specified event are canceled.
146           backgroundTaskManager.off("continuousTaskCancel", callback);
147           console.info(`Succeeded in operationing OffContinuousTaskCancel.`);
148        } catch (error) {
149           console.error(`Operation OffContinuousTaskCancel failed. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
150        }
151      }
152
153      startContinuousTask() {
154        let wantAgentInfo: wantAgent.WantAgentInfo = {
155          // List of operations to be executed after the notification is clicked.
156          // Add the bundleName and abilityName of the application to start.
157          wants: [
158            {
159              bundleName: "com.example.myapplication",
160              abilityName: "MainAbility"
161            }
162          ],
163          // Specify the action to perform (starting the ability) after the notification message is clicked.
164          actionType: wantAgent.OperationType.START_ABILITY,
165          // Custom request code.
166          requestCode: 0,
167          // Execution attribute of the operation to perform after the notification is clicked.
168          actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
169        };
170
171        try {
172          // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
173          wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
174            try {
175              let list: Array<string> = ["audioRecording"];
176              backgroundTaskManager.startBackgroundRunning(this.context, list, wantAgentObj).then((res: backgroundTaskManager.ContinuousTaskNotification) => {
177                console.info("Operation startBackgroundRunning succeeded");
178                // Execute the continuous task logic, for example, recording.
179              }).catch((error: BusinessError) => {
180                console.error(`Failed to Operation startBackgroundRunning. code is ${error.code} message is ${error.message}`);
181              });
182            } catch (error) {
183              console.error(`Failed to Operation startBackgroundRunning. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
184            }
185          });
186        } catch (error) {
187          console.error(`Failed to Operation getWantAgent. code is ${(error as BusinessError).code} message is ${(error as BusinessError).message}`);
188        }
189      }
190
191
192      stopContinuousTask() {
193         backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
194           console.info(`Succeeded in operationing stopBackgroundRunning.`);
195         }).catch((err: BusinessError) => {
196           console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
197         });
198      }
199
200      build() {
201        Row() {
202          Column() {
203            Text("Index")
204              .fontSize(50)
205              .fontWeight(FontWeight.Bold)
206
207           Button() {
208              Text('Request continuous task').fontSize(25).fontWeight(FontWeight.Bold)
209            }
210            .type(ButtonType.Capsule)
211            .margin({ top: 10 })
212            .backgroundColor('#0D9FFB')
213            .width(250)
214            .height(40)
215            .onClick(() => {
216              // Request a continuous task by clicking a button.
217              this.startContinuousTask();
218            })
219
220            Button() {
221              Text('Cancel continuous task').fontSize (25).fontWeight (FontWeight.Bold)
222            }
223            .type(ButtonType.Capsule)
224            .margin({ top: 10 })
225            .backgroundColor('#0D9FFB')
226            .width(250)
227            .height(40)
228            .onClick(() => {
229              // Stop the continuous task.
230
231              // Cancel the continuous task by clicking a button.
232              this.stopContinuousTask();
233            })
234
235            Button() {
236              Text('Register a callback for canceling a continuous task').fontSize (25).fontWeight(FontWeight.Bold)
237            }
238            .type(ButtonType.Capsule)
239            .margin({ top: 10 })
240            .backgroundColor('#0D9FFB')
241            .width(250)
242            .height(40)
243            .onClick(() => {
244              // Use a button to register a callback for canceling a continuous task.
245              this.OnContinuousTaskCancel();
246            })
247
248            Button() {
249              Text('Unregister a callback for canceling a continuous task').fontSize (25).fontWeight(FontWeight.Bold)
250            }
251            .type(ButtonType.Capsule)
252            .margin({ top: 10 })
253            .backgroundColor('#0D9FFB')
254            .width(250)
255            .height(40)
256            .onClick(() => {
257              // Use a button to unregister a callback for canceling a continuous task.
258              this.OffContinuousTaskCancel();
259            })
260          }
261          .width('100%')
262        }
263        .height('100%')
264      }
265    }
266   ```
267   <!--Del-->
268
269   The code snippet below shows how an application requests a continuous task across devices or applications. When a continuous task is executed across devices or applications in the background, the UIAbility can be created and run in the background in call mode. For details, see [Using Call to Implement UIAbility Interaction (for System Applications Only)](../application-models/uiability-intra-device-interaction.md#using-call-to-implement-uiability-interaction-for-system-applications-only) and [Using Cross-Device Call](../application-models/hop-multi-device-collaboration.md#using-cross-device-call).
270
271   ```ts
272    const MSG_SEND_METHOD: string = 'CallSendMsg'
273
274    let mContext: Context;
275
276    function startContinuousTask() {
277      let wantAgentInfo : wantAgent.WantAgentInfo = {
278        // List of operations to be executed after the notification is clicked.
279        wants: [
280          {
281            bundleName: "com.example.myapplication",
282            abilityName: "com.example.myapplication.MainAbility",
283          }
284        ],
285        // Type of the operation to perform after the notification is clicked.
286        actionType: wantAgent.OperationType.START_ABILITY,
287        // Custom request code.
288        requestCode: 0,
289        // Execution attribute of the operation to perform after the notification is clicked.
290        actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
291      };
292
293      // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
294      wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj : WantAgent) => {
295        backgroundTaskManager.startBackgroundRunning(mContext,
296          backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
297          console.info(`Succeeded in operationing startBackgroundRunning.`);
298        }).catch((err: BusinessError) => {
299          console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
300        });
301      });
302    }
303
304    function stopContinuousTask() {
305      backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
306        console.info(`Succeeded in operationing stopBackgroundRunning.`);
307      }).catch((err: BusinessError) => {
308        console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
309      });
310    }
311
312    class MyParcelable implements rpc.Parcelable {
313      num: number = 0;
314      str: string = '';
315
316      constructor(num: number, string: string) {
317        this.num = num;
318        this.str = string;
319      }
320
321      marshalling(messageSequence: rpc.MessageSequence) {
322        messageSequence.writeInt(this.num);
323        messageSequence.writeString(this.str);
324        return true;
325      }
326
327      unmarshalling(messageSequence: rpc.MessageSequence) {
328        this.num = messageSequence.readInt();
329        this.str = messageSequence.readString();
330        return true;
331      }
332    }
333
334    function sendMsgCallback(data: rpc.MessageSequence) {
335      console.info('BgTaskAbility funcCallBack is called ' + data);
336      let receivedData: MyParcelable = new MyParcelable(0, '');
337      data.readParcelable(receivedData);
338      console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
339      // You can execute different methods based on the str value in the sequenceable data sent by the caller object.
340      if (receivedData.str === 'start_bgtask') {
341        // Request a continuous task.
342        startContinuousTask();
343      } else if (receivedData.str === 'stop_bgtask') {
344        // Cancel the continuous task.
345        stopContinuousTask();
346      }
347      return new MyParcelable(10, 'Callee test');
348    }
349
350    export default class BgTaskAbility extends UIAbility {
351      // Create an ability.
352      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
353        console.info("[Demo] BgTaskAbility onCreate");
354        try {
355          this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
356        } catch (error) {
357          console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`);
358        }
359        mContext = this.context;
360      }
361
362      // Destroy an ability.
363      onDestroy() {
364        console.info('[Demo] BgTaskAbility onDestroy');
365      }
366
367      onWindowStageCreate(windowStage: window.WindowStage) {
368        console.info('[Demo] BgTaskAbility onWindowStageCreate');
369
370        windowStage.loadContent('pages/Index', (error, data) => {
371          if (error.code) {
372            console.error(`load content failed with error ${JSON.stringify(error)}`);
373            return;
374          }
375          console.info(`load content succeed with data ${JSON.stringify(data)}`);
376        });
377      }
378
379      onWindowStageDestroy() {
380        console.info('[Demo] BgTaskAbility onWindowStageDestroy');
381      }
382
383      onForeground() {
384        console.info('[Demo] BgTaskAbility onForeground');
385      }
386
387      onBackground() {
388        console.info('[Demo] BgTaskAbility onBackground');
389      }
390    };
391   ```
392
393   <!--DelEnd-->
394
395<!--Del-->
396### FA Model
397
3981. Start and connect to a ServiceAbility.
399
400   - If no user interaction is required, use **startAbility()** to start the ServiceAbility. For details, see [ServiceAbility Component](../application-models/serviceability-overview.md). In the **onStart** callback of the ServiceAbility, call the APIs to request and cancel continuous tasks.
401
402   - If user interaction is required (for example, in music playback scenarios), use **connectAbility()** to start and connect to the ServiceAbility. For details, see [ServiceAbility Component](../application-models/serviceability-overview.md). After obtaining the agent of the ServiceAbility, the application can communicate with the ServiceAbility and control the request and cancellation of continuous tasks.
403
4042. Configure permissions and declare the continuous task type.
405
406   Declare the **ohos.permission.KEEP_BACKGROUND_RUNNING** permission in the **config.json** file. For details, see [Declaring Permissions](../security/AccessToken/declare-permissions.md). In addition, declare the continuous task type for the ServiceAbility.
407
408   ```json
409   "module": {
410       "package": "com.example.myapplication",
411       "abilities": [
412           {
413               "backgroundModes": [
414               "audioRecording",
415               ], // Background mode
416               "type": "service"  // The ability type is Service.
417           }
418       ],
419       "reqPermissions": [
420           {
421               "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
422           }
423       ]
424   }
425   ```
426
4273. Import the modules.
428
429   ```js
430    import { backgroundTaskManager } from '@kit.BackgroundTasksKit';
431    import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit';
432    import { window } from '@kit.ArkUI';
433    import { rpc } from '@kit.IPCKit'
434    import { BusinessError } from '@kit.BasicServicesKit';
435    import { wantAgent, WantAgent } from '@kit.AbilityKit';
436   ```
437
4384. Request and cancel a continuous task. In the ServiceAbility, call [startBackgroundRunning](#available-apis) and [stopBackgroundRunning](#available-apis) to request and cancel a continuous task. Use JavaScript code to implement this scenario.
439
440   ```js
441    function startContinuousTask() {
442      let wantAgentInfo: wantAgent.WantAgentInfo = {
443        // List of operations to be executed after the notification is clicked.
444        wants: [
445          {
446            bundleName: "com.example.myapplication",
447            abilityName: "com.example.myapplication.MainAbility"
448          }
449        ],
450        // Type of the operation to perform after the notification is clicked.
451        actionType: wantAgent.OperationType.START_ABILITY,
452        // Custom request code.
453        requestCode: 0,
454        // Execution attribute of the operation to perform after the notification is clicked.
455        actionFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
456      };
457
458      // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
459      wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj: WantAgent) => {
460        backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
461          backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
462          console.info(`Succeeded in operationing startBackgroundRunning.`);
463        }).catch((err: BusinessError) => {
464          console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
465        });
466      });
467    }
468
469    function stopContinuousTask() {
470      backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
471        console.info(`Succeeded in operationing stopBackgroundRunning.`);
472      }).catch((err: BusinessError) => {
473        console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
474      });
475    }
476
477    async function processAsyncJobs() {
478      // Execute the continuous task.
479
480      // After the continuous task is complete, call the API to release resources.
481      stopContinuousTask();
482    }
483
484    let mMyStub: MyStub;
485
486    // Start the service by calling connectAbility().
487    class MyStub extends rpc.RemoteObject {
488      constructor(des: string) {
489        super(des);
490      }
491
492      onRemoteRequest(code: number, data: rpc.MessageParcel, reply: rpc.MessageParcel, option: rpc.MessageOption) {
493        console.log('ServiceAbility onRemoteRequest called');
494        // Custom request code.
495        if (code === 1) {
496          // Receive the request code for requesting a continuous task.
497          startContinuousTask();
498          // Execute the continuous task.
499        } else if (code === 2) {
500          // Receive the request code for canceling the continuous task.
501          stopContinuousTask();
502        } else {
503          console.log('ServiceAbility unknown request code');
504        }
505        return true;
506      }
507    }
508
509    // Start the service by calling startAbility().
510    class ServiceAbility {
511      onStart(want: Want) {
512        console.info('ServiceAbility onStart');
513        mMyStub = new MyStub("ServiceAbility-test");
514        // Call the API to start the task.
515        startContinuousTask();
516        processAsyncJobs();
517      }
518
519      onStop() {
520        console.info('ServiceAbility onStop');
521      }
522
523      onConnect(want: Want) {
524        console.info('ServiceAbility onConnect');
525        return mMyStub;
526      }
527
528      onReconnect(want: Want) {
529        console.info('ServiceAbility onReconnect');
530      }
531
532      onDisconnect() {
533        console.info('ServiceAbility onDisconnect');
534      }
535
536      onCommand(want: Want, startId: number) {
537        console.info('ServiceAbility onCommand');
538      }
539    }
540
541    export default new ServiceAbility();
542    ```
543<!--DelEnd-->
544
545