background-task-dev-guide.md 8.5 KB
Newer Older
廖康康 已提交
1 2 3 4 5 6 7 8 9
# 后台任务开发指导

## 场景介绍

应用或业务模块处于后台(无可见界面)时,如果有需要继续执行或者后续执行的业务,可基于业务类型,申请短时任务延迟挂起(Suspend)或者长时任务避免进入挂起状态。


## 接口说明

Z
zhangxin_T 已提交
10
```js
廖康康 已提交
11 12 13
import backgroundTaskManager from '@ohos.backgroundTaskManager';
```

Z
zhangxin_T 已提交
14 15
## 短时任务

廖康康 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
**表1** backgroundTaskManager主要接口

| 接口名 | 描述 |
| -------- | -------- |
| function&nbsp;requestSuspendDelay(reason:&nbsp;string,&nbsp;callback:&nbsp;Callback&lt;void&gt;):&nbsp;**DelaySuspendInfo**; | 后台应用申请延迟挂起。<br/>延迟挂起时间一般情况下默认值为180000,低电量(依据系统低电量广播)时默认值为60000。 |
| 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;; | 获取应用程序进入挂起状态前的剩余时间。(requestId从requestSuspendDelay的返回值获取)<br/>提供两种异步方法,使用Callback形式其任务执行结果以参数形式提供给回调函数,Promise形式则返回一个Promise对象。 |
| function&nbsp;cancelSuspendDelay(requestId:&nbsp;number):&nbsp;void; | 取消延迟挂起。(requestId从requestSuspendDelay的返回值获取) |

**表2** DelaySuspendInfo包含参数

| 参数名 | 类型 | 是否必选 | 描述 |
| -------- | -------- | -------- | -------- |
| requestId | number | 是 | 延迟挂起的请求ID。 |
| actualDelayTime | number | 是 | 应用的实际挂起延迟时间,以毫秒为单位。 |


## 开发步骤

Z
zhangxin_T 已提交
34

廖康康 已提交
35
1. 申请延迟挂起
Z
bugfix  
zhangxin_T 已提交
36

Z
zhangxin_T 已提交
37 38 39 40 41 42 43 44 45 46 47
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';

let myReason = 'test requestSuspendDelay';
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
    console.info("Request suspend delay will time out.");
});

var id = delayInfo.requestId;console.info("requestId is: " + id);
```

廖康康 已提交
48 49

2. 获取进入挂起前的剩余时间
Z
bugfix  
zhangxin_T 已提交
50

Z
zhangxin_T 已提交
51 52 53 54 55 56
```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);
});
廖康康 已提交
57 58
   ```

Z
zhangxin_T 已提交
59

廖康康 已提交
60
3. 取消延迟挂起
Z
bugfix  
zhangxin_T 已提交
61

Z
zhangxin_T 已提交
62 63 64
```js
backgroundTaskManager.cancelSuspendDelay(id);
```
廖康康 已提交
65 66 67 68


## 开发实例

Z
zhangxin_T 已提交
69
```js
廖康康 已提交
70 71
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay';
Z
zhangxin_T 已提交
72

廖康康 已提交
73
// 申请延迟挂起
update  
廖康康 已提交
74
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
update  
廖康康 已提交
75
    console.info("Request suspend delay will time out.");
廖康康 已提交
76
});
Z
zhangxin_T 已提交
77

廖康康 已提交
78 79 80 81 82
// 打印延迟挂起信息
var id = delayInfo.requestId;
var time = delayInfo.actualDelayTime;
console.info("The requestId is: " + id);
console.info("The actualDelayTime is: " + time);
Z
zhangxin_T 已提交
83

廖康康 已提交
84 85 86 87 88 89
// 获取应用程序进入挂起状态前的剩余时间
backgroundTaskManager.getRemainingDelayTime(id).then( res => {
    console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res));
}).catch( err => {
    console.log('promise => Operation failed. Cause: ' + err.data);
});
Z
zhangxin_T 已提交
90

廖康康 已提交
91 92 93
// 取消延迟挂起
backgroundTaskManager.cancelSuspendDelay(id);
```
Z
zhangxin_T 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107

## 长时任务

### 权限

ohos.permission.KEEP_BACKGROUND_RUNNING

**表3** 长时任务主要接口

| 接口名 | 描述 |
| -------- | -------- |
| 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;; | 服务启动后,向系统申请长时任务,使服务一直保持后台运行 |
| function stopBackgroundRunning(context: Context, callback: AsyncCallback&lt;void&gt;): void;<br/>function stopBackgroundRunning(context: Context): Promise&lt;void&gt;; | 停止后台长时任务的运行 |

Z
bugfix  
zhangxin_T 已提交
108 109

**表4** 后台模式类型
Z
zhangxin_T 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| 参数名 | id值 | 描述 |
| -------- | -------- | -------- |
| DATA_TRANSFER           | 1 | 数据传输 |
| AUDIO_PLAYBACK          | 2 | 音频播放 |
| AUDIO_RECORDING         | 3 | 录音 |
| LOCATION                | 4 | 定位导航 |
| BLUETOOTH_INTERACTION   | 5 | 蓝牙相关 |
| MULTI_DEVICE_CONNECTION | 6 | 多设备互联 |
| WIFI_INTERACTION        | 7 | WLAN相关(系统保留) |
| VOIP                    | 8 | 音视频通话(系统保留) |
| TASK_KEEPING            | 9 | 计算任务(仅供PC使用) |


## 开发步骤

Z
bugfix  
zhangxin_T 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
1. 在config.json文件中配置后台模式参数和权限

```json
"abilities": [
    {
        "visible": true,
        "backgroundModes": [
          "dataTransfer",
          "audioPlayback"
        ],
        "srcPath": "Service",
        "name": ".Service",
        "icon": "$media:icon",
        "srcLanguage": "js",
        "description": "$string:description_service",
        "type": "service"
    },
],
"defPermissions": [
    {
    "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
    }
],
"reqPermissions": [
    {
    "name": "ohos.permission.KEEP_BACKGROUND_RUNNING"
    }
]
```

Z
zhangxin_T 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
1. 申请长时任务

```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]
};

Z
bugfix  
zhangxin_T 已提交
174
// 通过wantAgent模块的getWantAgent方法获取WantAgent对象
Z
zhangxin_T 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
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);
    });
});

```

2. 停止长时任务

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

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

```

## 开发实例

当服务启动后,在serviceAbility的onStart回调方法中,调用长时任务的申请接口,声明此服务需要在后台长时运行。在onStop回调方法里,调用长时任务取消接口,声明取消长时任务。
在service.js文件中:
```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]
    };

Z
bugfix  
zhangxin_T 已提交
222
    // 通过wantAgent模块的getWantAgent方法获取WantAgent对象
Z
zhangxin_T 已提交
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
    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');
    }
};
```