background-task-dev-guide.md 9.5 KB
Newer Older
W
wusongqing 已提交
1 2 3 4 5 6 7 8 9
# Background Task Management Development

## When to Use

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.


## Available APIs

W
wusongqing 已提交
10
```js
W
wusongqing 已提交
11 12 13
import backgroundTaskManager from '@ohos.backgroundTaskManager';
```

W
wusongqing 已提交
14 15 16
## Transient Tasks

**Table 1** Main APIs for transient tasks
W
wusongqing 已提交
17 18 19

| API| Description|
| -------- | -------- |
W
wusongqing 已提交
20 21
| function&nbsp;requestSuspendDelay(reason:&nbsp;string,&nbsp;callback:&nbsp;Callback&lt;void&gt;):&nbsp;**DelaySuspendInfo**; | Requests delayed suspension after the application switches to the background.<br>The default duration of delayed suspension is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.|
| function&nbsp;getRemainingDelayTime(requestId:&nbsp;number,&nbsp;callback:&nbsp;AsyncCallback&lt;number&gt;):&nbsp;void;<br>function&nbsp;getRemainingDelayTime(requestId:&nbsp;number):&nbsp;Promise&lt;number&gt;; | Obtains the remaining duration before the application is suspended. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)<br>Two asynchronous methods are provided: callback and promise.|
W
wusongqing 已提交
22 23 24 25 26 27 28 29 30 31 32 33
| function&nbsp;cancelSuspendDelay(requestId:&nbsp;number):&nbsp;void; | Cancels the suspension delay. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)|

**Table 2** Parameters in DelaySuspendInfo

| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| requestId | number | Yes| ID of the suspension delay request.|
| actualDelayTime | number | Yes| Actual suspension delay duration of the application, in milliseconds.|


## How to Develop

W
wusongqing 已提交
34

W
wusongqing 已提交
35
1. Request a suspension delay.
W
wusongqing 已提交
36 37 38

    ```js
    import backgroundTaskManager from '@ohos.backgroundTaskManager';
W
wusongqing 已提交
39
    
W
wusongqing 已提交
40 41 42 43
    let myReason = 'test requestSuspendDelay';
    let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
        console.info("Request suspension delay will time out.");
    });
W
wusongqing 已提交
44
    
W
wusongqing 已提交
45 46 47
    var id = delayInfo.requestId;console.info("requestId is: " + id);
    ```

W
wusongqing 已提交
48 49

2. Obtain the remaining duration before the application is suspended.
W
wusongqing 已提交
50 51 52 53 54 55 56 57 58

    ```js
    backgroundTaskManager.getRemainingDelayTime(id).then( res => {
        console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res));
    }).catch( err => {
        console.log('promise => Operation failed. Cause: ' + err.data);
    });
    ```

W
wusongqing 已提交
59 60

3. Cancel the suspension delay.
W
wusongqing 已提交
61 62 63 64

    ```js
    backgroundTaskManager.cancelSuspendDelay(id);
    ```
W
wusongqing 已提交
65 66 67 68


## Development Examples

W
wusongqing 已提交
69
```js
W
wusongqing 已提交
70 71
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay';
W
wusongqing 已提交
72

W
wusongqing 已提交
73
// Request a suspension delay.
W
wusongqing 已提交
74 75 76
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
    console.info("Request suspension delay will time out.");
});
W
wusongqing 已提交
77

W
wusongqing 已提交
78 79 80 81 82
// 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 已提交
83

W
wusongqing 已提交
84 85 86 87 88 89
// Obtain the remaining duration before the application is suspended.
backgroundTaskManager.getRemainingDelayTime(id).then( res => {
    console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res));
}).catch( err => {
    console.log('promise => Operation failed. Cause: ' + err.data);
});
W
wusongqing 已提交
90

W
wusongqing 已提交
91 92 93
// Cancel the suspension delay.
backgroundTaskManager.cancelSuspendDelay(id);
```
W
wusongqing 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

## Continuous Tasks

### Required Permissions

ohos.permission.KEEP_BACKGROUND_RUNNING

**Table 3** Main APIs for continuous tasks

| API| Description|
| -------- | -------- |
| function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback&lt;void&gt;): void;<br>function 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.|
| function stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void;<br>function stopBackgroundRunning(context: Context): Promise&lt;void&gt;; | Cancels the continuous task.|


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

**Table 4** Background modes
W
wusongqing 已提交
112 113 114 115 116 117 118 119 120 121 122 123

| Name| ID Value| Description| 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 PC only).| taskKeeping |
W
wusongqing 已提交
124 125 126 127


## How to Develop

W
wusongqing 已提交
128
1. Configure the continuous task permission and background mode type in the **config.json** file, with the ability type set to **service**.
W
wusongqing 已提交
129 130 131

    ```json
    "module": {
W
wusongqing 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
      "package": "com.example.myapplication",
      
      "abilities": [
      
        {
          "backgroundModes": [
            "dataTransfer",
            "location",
            
          ],
          
          "type": "service"
        }
      ],
      "defPermissions": [
        {
          "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
        }
      ],
      "reqPermissions": [
        {
          "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
        }
      ]
W
wusongqing 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
    }
    ```

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,
        wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG]
    };

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

3. Cancel the continuous task.

    ```js
    import backgroundTaskManager from '@ohos.backgroundTaskManager';
    import featureAbility from '@ohos.ability.featureAbility';
W
wusongqing 已提交
194
    
W
wusongqing 已提交
195 196 197 198 199
    backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
        console.info("Operation succeeded");
    }).catch((err) => {
        console.error("Operation failed Cause: " + err);
    });
W
wusongqing 已提交
200
    
W
wusongqing 已提交
201 202 203 204 205 206 207 208 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 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
    ```

## Development Examples

After a service is started, call the API for requesting a continuous task in the **onStart** callback of the Service ability to declare that the service needs to run in the background for a long time. In the **onStop** callback, call the API for canceling the continuous task.
In the **service.js** file:

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

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

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

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

export default {
    onStart(want) {
        console.info('ServiceAbility onStart');
        startBackgroundRunning();
    },
    onStop() {
        console.info('ServiceAbility onStop');
        stopBackgroundRunning();
    },
    onConnect(want) {
        console.info('ServiceAbility onConnect');
        return {};
    },
    onReconnect(want) {
        console.info('ServiceAbility onReconnect');
    },
    onDisconnect() {
        console.info('ServiceAbility onDisconnect');
    },
    onCommand(want, restart, startId) {
        console.info('ServiceAbility onCommand');
    }
};
```
新手
引导
客服 返回
顶部