background-task-dev-guide.md 17.3 KB
Newer Older
W
wusongqing 已提交
1 2 3 4
# Background Task Management Development

## When to Use

W
wusongqing 已提交
5
If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type.
W
wusongqing 已提交
6

W
wusongqing 已提交
7 8
## Transient Tasks

W
wusongqing 已提交
9 10
### Available APIs

W
wusongqing 已提交
11
**Table 1** Main APIs for transient tasks
W
wusongqing 已提交
12

W
wusongqing 已提交
13 14 15 16 17
| API                                     | Description                                      |
| ---------------------------------------- | ---------------------------------------- |
| requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo) | Requests delayed suspension after the application switches to the background.<br>The default duration value of delayed suspension is 180000 when the battery level is normal and 60000 when the battery level is low.|
| getRemainingDelayTime(requestId: number): Promise&lt;number&gt; | Obtains the remaining duration before the application is suspended.<br>This API uses a promise to return the result.  |
| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay.                                 |
W
wusongqing 已提交
18 19


W
wusongqing 已提交
20
### How to Develop
W
wusongqing 已提交
21

W
wusongqing 已提交
22

W
wusongqing 已提交
23
1. Request a suspension delay.
W
wusongqing 已提交
24 25 26

    ```js
    import backgroundTaskManager from '@ohos.backgroundTaskManager';
W
wusongqing 已提交
27

W
wusongqing 已提交
28 29 30 31
    let myReason = 'test requestSuspendDelay';
    let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
        console.info("Request suspension delay will time out.");
    });
W
wusongqing 已提交
32

W
wusongqing 已提交
33 34
    var id = delayInfo.requestId;
    console.info("requestId is: " + id);
W
wusongqing 已提交
35 36
    ```

W
wusongqing 已提交
37 38

2. Obtain the remaining duration before the application is suspended.
W
wusongqing 已提交
39 40 41

    ```js
    backgroundTaskManager.getRemainingDelayTime(id).then( res => {
W
wusongqing 已提交
42
        console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
W
wusongqing 已提交
43
    }).catch( err => {
W
wusongqing 已提交
44
        console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code);
W
wusongqing 已提交
45 46 47
    });
    ```

W
wusongqing 已提交
48 49

3. Cancel the suspension delay.
W
wusongqing 已提交
50 51 52 53

    ```js
    backgroundTaskManager.cancelSuspendDelay(id);
    ```
W
wusongqing 已提交
54 55


W
wusongqing 已提交
56
### Development Examples
W
wusongqing 已提交
57

W
wusongqing 已提交
58
```js
W
wusongqing 已提交
59 60
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay';
W
wusongqing 已提交
61

W
wusongqing 已提交
62
// Request a suspension delay.
W
wusongqing 已提交
63 64 65
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
    console.info("Request suspension delay will time out.");
});
W
wusongqing 已提交
66

W
wusongqing 已提交
67 68 69 70 71
// Print the suspension delay information.
var id = delayInfo.requestId;
var time = delayInfo.actualDelayTime;
console.info("The requestId is: " + id);
console.info("The actualDelayTime is: " + time);
W
wusongqing 已提交
72

W
wusongqing 已提交
73 74
// Obtain the remaining duration before the application is suspended.
backgroundTaskManager.getRemainingDelayTime(id).then( res => {
W
wusongqing 已提交
75
    console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
W
wusongqing 已提交
76
}).catch( err => {
W
wusongqing 已提交
77
    console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code);
W
wusongqing 已提交
78
});
W
wusongqing 已提交
79

W
wusongqing 已提交
80 81 82
// Cancel the suspension delay.
backgroundTaskManager.cancelSuspendDelay(id);
```
W
wusongqing 已提交
83 84 85 86 87 88 89

## Continuous Tasks

### Required Permissions

ohos.permission.KEEP_BACKGROUND_RUNNING

W
wusongqing 已提交
90 91 92
### Available APIs

**Table 2** Main APIs for continuous tasks
W
wusongqing 已提交
93

W
wusongqing 已提交
94 95
| API                                     | Description                          |
| ---------------------------------------- | ---------------------------- |
W
wusongqing 已提交
96
| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt; | Requests a continuous task from the system so that the application keeps running in the background.|
W
wusongqing 已提交
97
| stopBackgroundRunning(context: Context): Promise&lt;void&gt; | Cancels the continuous task.                |
W
wusongqing 已提交
98 99


W
wusongqing 已提交
100
For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-wantAgent.md).
W
wusongqing 已提交
101

W
wusongqing 已提交
102
**Table 3** Background modes
W
wusongqing 已提交
103

W
wusongqing 已提交
104 105 106 107 108 109 110 111 112 113 114
| Name                    | ID | Description            | Configuration Item                  |
| ----------------------- | ---- | -------------- | --------------------- |
| DATA_TRANSFER           | 1    | Data transfer.          | dataTransfer          |
| AUDIO_PLAYBACK          | 2    | Audio playback.          | audioPlayback         |
| AUDIO_RECORDING         | 3    | Audio recording.            | audioRecording        |
| LOCATION                | 4    | Positioning and navigation.          | location              |
| BLUETOOTH_INTERACTION   | 5    | Bluetooth-related task.          | bluetoothInteraction  |
| MULTI_DEVICE_CONNECTION | 6    | Multi-device connection.         | multiDeviceConnection |
| WIFI_INTERACTION        | 7    | WLAN-related task (reserved).  | wifiInteraction       |
| VOIP                    | 8    | Voice and video call (reserved).   | voip                  |
| TASK_KEEPING            | 9    | Computing task (for specific devices only).| taskKeeping           |
W
wusongqing 已提交
115 116


W
wusongqing 已提交
117
### How to Develop
W
wusongqing 已提交
118

W
wusongqing 已提交
119 120
Development on the FA model:

W
wusongqing 已提交
121
1. Create an API version 8 project. Then right-click the project directory and choose **New > Ability > Service Ability** to create a Service ability. Configure the continuous task permission and background mode type in the **config.json** file, with the ability type set to **service**.
W
wusongqing 已提交
122

W
wusongqing 已提交
123
    ```
W
wusongqing 已提交
124
    "module": {
W
wusongqing 已提交
125 126 127 128 129
      "package": "com.example.myapplication",
      "abilities": [
        {
          "backgroundModes": [
            "dataTransfer",
W
wusongqing 已提交
130 131 132
            "location"
          ], // Background mode
          "type": "service"  // The ability type is service.
W
wusongqing 已提交
133 134 135 136
        }
      ],
      "reqPermissions": [
        {
W
wusongqing 已提交
137
          "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
W
wusongqing 已提交
138 139
        }
      ]
W
wusongqing 已提交
140 141
    }
    ```
W
wusongqing 已提交
142

W
wusongqing 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
2. Request a continuous task.

    ```js
    import backgroundTaskManager from '@ohos.backgroundTaskManager';
    import featureAbility from '@ohos.ability.featureAbility';
    import wantAgent from '@ohos.wantAgent';

    let wantAgentInfo = {
        wants: [
            {
                bundleName: "com.example.myapplication",
                abilityName: "com.example.myapplication.MainAbility"
            }
        ],
        operationType: wantAgent.OperationType.START_ABILITY,
        requestCode: 0,
W
wusongqing 已提交
159
        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
W
wusongqing 已提交
160 161
    };

W
wusongqing 已提交
162
    // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
W
wusongqing 已提交
163 164 165
    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
        backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
            backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
W
wusongqing 已提交
166
            console.info("Operation startBackgroundRunning succeeded");
W
wusongqing 已提交
167
        }).catch((err) => {
W
wusongqing 已提交
168
            console.error("Operation startBackgroundRunning failed Cause: " + err);
W
wusongqing 已提交
169 170 171 172 173 174 175 176 177
        });
    });
    ```

3. Cancel the continuous task.

    ```js
    import backgroundTaskManager from '@ohos.backgroundTaskManager';
    import featureAbility from '@ohos.ability.featureAbility';
W
wusongqing 已提交
178

W
wusongqing 已提交
179
    backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
W
wusongqing 已提交
180
        console.info("Operation stopBackgroundRunning succeeded");
W
wusongqing 已提交
181
    }).catch((err) => {
W
wusongqing 已提交
182
        console.error("Operation stopBackgroundRunning failed Cause: " + err);
W
wusongqing 已提交
183
    });
W
wusongqing 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

    ```

Development on the stage model:

1. Create an API version 9 project. Then right-click the project directory and choose **New > Ability** to create an ability. Configure the continuous task permission and background mode type in the **module.json5** file.

    ```
    "module": {
      "abilities": [
        {
          "backgroundModes": [
            "dataTransfer",
            "location"
          ], // Background mode
        }
      ],
      "requestPermissions": [
        {
          "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
        }
      ]
    }
W
wusongqing 已提交
207 208
    ```

W
wusongqing 已提交
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
2. Request a continuous task.

    ```ts
    import backgroundTaskManager from '@ohos.backgroundTaskManager';
    import wantAgent from '@ohos.wantAgent';

    let wantAgentInfo = {
        wants: [
            {
                bundleName: "com.example.myapplication",
                abilityName: "com.example.myapplication.MainAbility"
            }
        ],
        operationType: wantAgent.OperationType.START_ABILITY,
        requestCode: 0,
        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
    };

    // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
        backgroundTaskManager.startBackgroundRunning(this.context,
            backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
            console.info("Operation startBackgroundRunning succeeded");
        }).catch((err) => {
            console.error("Operation startBackgroundRunning failed Cause: " + err);
        });
    });
    ```

3. Cancel the continuous task.

    ```ts
    import backgroundTaskManager from '@ohos.backgroundTaskManager';

    backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
        console.info("Operation stopBackgroundRunning succeeded");
    }).catch((err) => {
        console.error("Operation stopBackgroundRunning failed Cause: " + err);
    });

    ```


W
wusongqing 已提交
252
### Development Examples
W
wusongqing 已提交
253 254 255

Development on the FA model:

W
wusongqing 已提交
256 257 258
For details about how to use the Service ability in the FA model, see [Service Ability Development](../ability/fa-serviceability.md).

If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the Service ability. In the **onStart** callback of the Service ability, call **startBackgroundRunning()** to declare that the Service ability needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources.
W
wusongqing 已提交
259

W
wusongqing 已提交
260
If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the Service ability. After obtaining the proxy of the Service ability, the application can communicate with the Service ability and control the request and cancellation of continuous tasks.
W
wusongqing 已提交
261 262 263 264 265

```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.wantAgent';
W
wusongqing 已提交
266
import rpc from "@ohos.rpc";
W
wusongqing 已提交
267 268 269

function startBackgroundRunning() {
    let wantAgentInfo = {
W
wusongqing 已提交
270
        // List of operations to be executed after the notification is clicked.
W
wusongqing 已提交
271 272 273 274 275 276
        wants: [
            {
                bundleName: "com.example.myapplication",
                abilityName: "com.example.myapplication.MainAbility"
            }
        ],
W
wusongqing 已提交
277
        // Type of the operation to perform after the notification is clicked.
W
wusongqing 已提交
278
        operationType: wantAgent.OperationType.START_ABILITY,
W
wusongqing 已提交
279
        // Custom request code.
W
wusongqing 已提交
280
        requestCode: 0,
W
wusongqing 已提交
281
        // Execution attribute of the operation to perform after the notification is clicked.
W
wusongqing 已提交
282
        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
W
wusongqing 已提交
283 284
    };

W
wusongqing 已提交
285
    // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
W
wusongqing 已提交
286 287 288
    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
        backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
            backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
W
wusongqing 已提交
289
            console.info("Operation startBackgroundRunning succeeded");
W
wusongqing 已提交
290
        }).catch((err) => {
W
wusongqing 已提交
291
            console.error("Operation startBackgroundRunning failed Cause: " + err);
W
wusongqing 已提交
292 293 294 295 296 297
        });
    });
}

function stopBackgroundRunning() {
    backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
W
wusongqing 已提交
298
        console.info("Operation stopBackgroundRunning succeeded");
W
wusongqing 已提交
299
    }).catch((err) => {
W
wusongqing 已提交
300
        console.error("Operation stopBackgroundRunning failed Cause: " + err);
W
wusongqing 已提交
301 302 303
    });
}

W
wusongqing 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
let mMyStub;

class MyStub extends rpc.RemoteObject {
    constructor(des) {
        if (typeof des === 'string') {
            super(des);
        } else {
            return null;
        }
    }
    onRemoteRequest(code, data, reply, option) {
        console.log('ServiceAbility onRemoteRequest called');
        // The meaning of code is user-defined.
        if (code === 1) {
            // Received the request code for requesting a continuous task.
            startContinuousTask();
            // Execute the continuous task.
        } else if (code === 2) {
            // Received the request code for canceling the continuous task.
            stopContinuousTask();
        } else {
            console.log('ServiceAbility unknown request code');
        }
        return true;
    }
}

W
wusongqing 已提交
331 332 333
export default {
    onStart(want) {
        console.info('ServiceAbility onStart');
W
wusongqing 已提交
334
        mMyStub = new MyStub("ServiceAbility-test");
W
wusongqing 已提交
335
        startBackgroundRunning();
W
wusongqing 已提交
336 337
        // Execute a specific continuous task in the background.
        stopBackgroundRunning();
W
wusongqing 已提交
338 339 340 341 342 343
    },
    onStop() {
        console.info('ServiceAbility onStop');
    },
    onConnect(want) {
        console.info('ServiceAbility onConnect');
W
wusongqing 已提交
344
        return mMyStub;
W
wusongqing 已提交
345 346 347 348 349 350 351 352 353 354 355 356
    },
    onReconnect(want) {
        console.info('ServiceAbility onReconnect');
    },
    onDisconnect() {
        console.info('ServiceAbility onDisconnect');
    },
    onCommand(want, restart, startId) {
        console.info('ServiceAbility onCommand');
    }
};
```
W
wusongqing 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480

Development on the stage model:

For details about the stage model, see [Stage Model Overview](../ability/stage-brief.md).
If an application needs to run a continuous task in the background, you can use **Call** to create and run an ability in the background. For details, see [Call Development](../ability/stage-call.md).

```ts
import Ability from '@ohos.application.Ability'
import backgroundTaskManager from '@ohos.backgroundTaskManager';
import wantAgent from '@ohos.wantAgent';

let mContext = null;

function startContinuousTask() {
    let wantAgentInfo = {
        // List of operations to be executed after the notification is clicked.
        wants: [
            {
                bundleName: "com.example.myapplication",
                abilityName: "com.example.myapplication.MainAbility"
            }
        ],
        // Type of the operation to perform after the notification is clicked.
        operationType: wantAgent.OperationType.START_ABILITY,
        // Custom request code.
        requestCode: 0,
        // Execution attribute of the operation to perform after the notification is clicked.
        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
    };

    // Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
    wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
        backgroundTaskManager.startBackgroundRunning(mContext,
            backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
            console.info("Operation startBackgroundRunning succeeded");
        }).catch((err) => {
            console.error("Operation startBackgroundRunning failed Cause: " + err);
        });
    });
}

function stopContinuousTask() {
    backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
        console.info("Operation stopBackgroundRunning succeeded");
    }).catch((err) => {
        console.error("Operation stopBackgroundRunning failed Cause: " + err);
    });
}

class MySequenceable {
    num: number = 0;
    str: String = "";

    constructor(num, string) {
        this.num = num;
        this.str = string;
    }

    marshalling(messageParcel) {
        messageParcel.writeInt(this.num);
        messageParcel.writeString(this.str);
        return true;
    }

    unmarshalling(messageParcel) {
        this.num = messageParcel.readInt();
        this.str = messageParcel.readString();
        return true;
    }
}

function sendMsgCallback(data) {
    console.info('BgTaskAbility funcCallBack is called ' + data)
    let receivedData = new Mysequenceable(0, "")
    data.readSequenceable(receivedData)
    console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`)
    if (receivedData.str === 'start_bgtask') {
        startContinuousTask()
    } else if (receivedData.str === 'stop_bgtask') {
        stopContinuousTask();
    }
    return new Mysequenceable(10, "Callee test");
}

export default class BgTaskAbility extends Ability {
    onCreate(want, launchParam) {
        console.info("[Demo] BgTaskAbility onCreate")
        this.callee.on("test", sendMsgCallback);

        try {
            this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
        } catch (error) {
            console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
        }
        mContext = this.context;
    }

    onDestroy() {
        console.info("[Demo] BgTaskAbility onDestroy")
    }

    onWindowStageCreate(windowStage) {
        console.info("[Demo] BgTaskAbility onWindowStageCreate")

        windowStage.loadContent("pages/second").then((data)=> {
            console.info(`load content succeed with data ${JSON.stringify(data)}`)
        }).catch((error)=>{
            console.error(`load content failed with error ${JSON.stringify(error)}`)
        })
    }

    onWindowStageDestroy() {
        console.info("[Demo] BgTaskAbility onWindowStageDestroy")
    }

    onForeground() {
        console.info("[Demo] BgTaskAbility onForeground")
    }

    onBackground() {
        console.info("[Demo] BgTaskAbility onBackground")
    }
};
```