js-apis-net-connection.md 37.3 KB
Newer Older
Z
zengyawen 已提交
1
# 网络连接管理
2

C
clevercong 已提交
3
网络连接管理提供管理网络一些基础能力,包括获取默认激活的数据网络、获取所有激活数据网络列表、开启关闭飞行模式、获取网络能力信息等功能。
C
clevercong 已提交
4

5 6
> **说明:**
>
Z
zengyawen 已提交
7
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8 9 10

## 导入模块

Z
zengyawen 已提交
11
```js
12 13 14 15 16 17 18
import connection from '@ohos.net.connection'
```

## connection.getDefaultNet

getDefaultNet(callback: AsyncCallback\<NetHandle>): void

Z
zengyawen 已提交
19
获取默认激活的数据网络,使用callback方式作为异步方法。
20 21 22 23 24 25 26

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
27 28 29
| 参数名   | 类型                                    | 必填 | 说明       |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<[NetHandle](#nethandle)> | 是   | 回调函数。 |
30 31 32

**示例:**

Z
zengyawen 已提交
33
```js
34 35 36 37 38 39 40 41 42 43
connection.getDefaultNet(function (error, netHandle) {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(netHandle))
})
```

## connection.getDefaultNet

getDefaultNet(): Promise\<NetHandle>

Z
zengyawen 已提交
44
获取默认激活的数据网络,使用Promise方式作为异步方法。
45 46 47 48 49 50 51

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**返回值:**

Z
zengyawen 已提交
52 53 54
| 类型                              | 说明                                  |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetHandle](#nethandle)> | 以Promise形式返回默认激活的数据网络。 |
55 56 57

**示例:**

Z
zengyawen 已提交
58
```js
59 60 61 62 63 64 65 66 67
connection.getDefaultNet().then(function (netHandle) {
    console.log(JSON.stringify(netHandle))
})
```

## connection.hasDefaultNet

hasDefaultNet(callback: AsyncCallback\<boolean>): void

Z
zengyawen 已提交
68
检查默认数据网络是否被激活,使用callback方式作为异步方法。
Z
zhuwenchao 已提交
69
默认数据网络:以太网>wifi>蜂窝,当只有一个网络为连接状态时,当前连接网络为默认数据网络。
70 71 72 73 74

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
75 76 77
| 参数名   | 类型                    | 必填 | 说明                                   |
| -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | 是   | 回调函数,默认数据网络被激活返回true。 |
78 79 80

**示例:**

Z
zengyawen 已提交
81
```js
82 83
connection.hasDefaultNet(function (error, has) {
    console.log(JSON.stringify(error))
C
clevercong 已提交
84
    console.log('has: ' + has)
85 86 87 88 89 90 91
})
```

## connection.hasDefaultNet

hasDefaultNet(): Promise\<boolean>

Z
zengyawen 已提交
92
检查默认数据网络是否被激活,使用Promise方式作为异步方法。
Z
zhuwenchao 已提交
93
默认数据网络:以太网>wifi>蜂窝,当只有一个网络为连接状态时,当前连接网络为默认数据网络。
94 95 96 97 98

**系统能力**:SystemCapability.Communication.NetManager.Core

**返回值:**

Z
zengyawen 已提交
99 100 101
| 类型              | 说明                                            |
| ----------------- | ----------------------------------------------- |
| Promise\<boolean> | 以Promise形式返回,默认数据网络被激活返回true。 |
102 103 104

**示例:**

Z
zengyawen 已提交
105
```js
106
connection.hasDefaultNet().then(function (has) {
C
clevercong 已提交
107
    console.log('has: ' + has)
108 109 110
})
```

C
clevercong 已提交
111 112 113 114
## connection.getAllNets

getAllNets(callback: AsyncCallback&lt;Array&lt;NetHandle&gt;&gt;): void

115
获取所有处于连接状态的网络列表,使用callback方式作为异步方法。
C
clevercong 已提交
116

C
clevercong 已提交
117 118 119
**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core
C
clevercong 已提交
120 121

**参数:**
122

C
clevercong 已提交
123 124 125 126 127 128
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | 是 | 回调函数。 |

**示例:**

Z
zengyawen 已提交
129
```js
C
clevercong 已提交
130 131 132 133 134 135 136 137 138 139 140
connection.getAllNets(function (error, nets) {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(nets))
});
```


## connection.getAllNets

getAllNets(): Promise&lt;Array&lt;NetHandle&gt;&gt;

141
获取所有处于连接状态的网络列表,使用promise方式作为异步方法。
C
clevercong 已提交
142

C
clevercong 已提交
143 144 145
**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core
C
clevercong 已提交
146 147

**返回值:**
148

C
clevercong 已提交
149 150 151 152 153 154
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;Array&lt;[NetHandle](#nethandle)&gt;&gt; | 以Promise形式返回激活的数据网络列表。 |

**示例:**

Z
zengyawen 已提交
155
```js
C
clevercong 已提交
156 157 158 159 160
connection.getAllNets().then(function (nets) {
    console.log(JSON.stringify(nets))
});
```

161 162 163 164
## connection.getConnectionProperties

getConnectionProperties(netHandle: NetHandle, callback: AsyncCallback\<ConnectionProperties>): void

Z
zengyawen 已提交
165
获取netHandle对应的网络的连接信息,使用callback方式作为异步方法。
166 167 168 169 170 171 172

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
173 174 175 176
| 参数名    | 类型                                                         | 必填 | 说明             |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle)                                      | 是   | 数据网络的句柄。 |
| callback  | AsyncCallback\<[ConnectionProperties](#connectionproperties)> | 是   | 回调函数。       |
177 178 179

**示例:**

Z
zengyawen 已提交
180
```js
181 182 183 184 185 186 187 188 189 190 191 192
connection.getDefaultNet().then(function (netHandle) {
    connection.getConnectionProperties(netHandle, function (error, info) {
        console.log(JSON.stringify(error))
        console.log(JSON.stringify(info))
    })
})
```

## connection.getConnectionProperties

getConnectionProperties(netHandle: NetHandle): Promise\<ConnectionProperties>

Z
zengyawen 已提交
193
获取netHandle对应的网络的连接信息,使用Promise方式作为异步方法。
194 195 196 197 198 199 200

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
201 202 203
| 参数名    | 类型                    | 必填 | 说明             |
| --------- | ----------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | 是   | 数据网络的句柄。 |
204 205 206

**返回值:**

Z
zengyawen 已提交
207 208 209
| 类型                                                    | 说明                              |
| ------------------------------------------------------- | --------------------------------- |
| Promise\<[ConnectionProperties](#connectionproperties)> | 以Promise形式返回网络的连接信息。 |
210 211 212

**示例:**

Z
zengyawen 已提交
213
```js
214 215 216 217 218 219 220 221 222 223 224
connection.getDefaultNet().then(function (netHandle) {
    connection.getConnectionProperties(netHandle).then(function (info) {
        console.log(JSON.stringify(info))
    })
})
```

## connection.getNetCapabilities

getNetCapabilities(netHandle: NetHandle, callback: AsyncCallback\<NetCapabilities>): void

Z
zengyawen 已提交
225
获取netHandle对应的网络的能力信息,使用callback方式作为异步方法。
226 227 228 229 230 231 232

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
233 234 235 236
| 参数名    | 类型                                                | 必填 | 说明             |
| --------- | --------------------------------------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle)                             | 是   | 数据网络的句柄。 |
| callback  | AsyncCallback\<[NetCapabilities](#netcapabilities)> | 是   | 回调函数。       |
237 238 239

**示例:**

Z
zengyawen 已提交
240
```js
241 242 243 244 245 246 247 248 249 250 251 252
connection.getDefaultNet().then(function (netHandle) {
    connection.getNetCapabilities(netHandle, function (error, info) {
        console.log(JSON.stringify(error))
        console.log(JSON.stringify(info))
    })
})
```

## connection.getNetCapabilities

getNetCapabilities(netHandle: NetHandle): Promise\<NetCapabilities>

Z
zengyawen 已提交
253
获取netHandle对应的网络的能力信息,使用Promise方式作为异步方法。
254 255 256 257 258 259 260

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
261 262 263
| 参数名    | 类型                    | 必填 | 说明             |
| --------- | ----------------------- | ---- | ---------------- |
| netHandle | [NetHandle](#nethandle) | 是   | 数据网络的句柄。 |
264 265 266

**返回值:**

Z
zengyawen 已提交
267 268 269
| 类型                                          | 说明                              |
| --------------------------------------------- | --------------------------------- |
| Promise\<[NetCapabilities](#netcapabilities)> | 以Promise形式返回网络的能力信息。 |
270 271 272

**示例:**

Z
zengyawen 已提交
273
```js
274 275 276 277 278 279 280
connection.getDefaultNet().then(function (netHandle) {
    connection.getNetCapabilities(netHandle).then(function (info) {
        console.log(JSON.stringify(info))
    })
})
```

C
clevercong 已提交
281 282 283 284
## connection.reportNetConnected

reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void

285
向网络管理报告网络处于可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。
286
使用callback方式作为异步方法。
C
clevercong 已提交
287

C
clevercong 已提交
288 289 290
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET

**系统能力**:SystemCapability.Communication.NetManager.Core
C
clevercong 已提交
291 292

**参数:**
293

C
clevercong 已提交
294 295 296 297 298 299 300
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |

**示例:**

Z
zengyawen 已提交
301
```js
C
clevercong 已提交
302 303 304 305 306 307 308 309 310 311 312 313
connection.getDefaultNet().then(function (netHandle) {
    connection.reportNetConnected(netHandle, function (error) {
        console.log(JSON.stringify(error))
    });
});
```


## connection.reportNetConnected

reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;

314
向网络管理报告网络处于可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。
315
使用promise方式作为异步方法。
C
clevercong 已提交
316

C
clevercong 已提交
317 318 319
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET

**系统能力**:SystemCapability.Communication.NetManager.Core
C
clevercong 已提交
320 321

**参数:**
322

C
clevercong 已提交
323 324 325 326 327 328 329 330 331 332 333
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |

**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | 以Promise形式返回执行结果。 |

**示例:**

Z
zengyawen 已提交
334
```js
C
clevercong 已提交
335 336 337 338 339 340 341 342 343 344 345 346
connection.getDefaultNet().then(function (netHandle) {
    connection.reportNetConnected(netHandle).then(function () {
        console.log(`report success`)
    });
});
```


## connection.reportNetDisconnected

reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void

347
向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。
348
使用callback方式作为异步方法。
C
clevercong 已提交
349

C
clevercong 已提交
350 351 352
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET

**系统能力**:SystemCapability.Communication.NetManager.Core
C
clevercong 已提交
353 354

**参数:**
355

C
clevercong 已提交
356 357 358 359 360 361 362
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |

**示例:**

Z
zengyawen 已提交
363
```js
C
clevercong 已提交
364 365 366 367 368 369 370 371 372 373 374 375
connection.getDefaultNet().then(function (netHandle) {
    connection.reportNetDisconnected(netHandle, function (error) {
        console.log(JSON.stringify(error))
    });
});
```


## connection.reportNetDisconnected

reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;

376
向网络管理报告网络处于不可用状态,调用此接口说明应用程序认为网络的可用性(ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED)与网络管理不一致。
377
使用promise方式作为异步方法。
C
clevercong 已提交
378

C
clevercong 已提交
379 380 381
**需要权限**:ohos.permission.GET_NETWORK_INFO 和 ohos.permission.INTERNET

**系统能力**:SystemCapability.Communication.NetManager.Core
C
clevercong 已提交
382 383

**参数:**
384

C
clevercong 已提交
385 386 387 388 389 390 391 392 393 394 395
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| netHandle | [NetHandle](#nethandle) | 是 | 数据网络的句柄,参考[NetHandle](#nethandle)。 |

**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | 以Promise形式返回执行结果。 |

**示例:**

Z
zengyawen 已提交
396
```js
C
clevercong 已提交
397 398 399 400 401 402 403
connection.getDefaultNet().then(function (netHandle) {
    connection.reportNetDisconnected(netHandle).then(function () {
        console.log(`report success`)
    });
});
```

404 405 406 407
## connection.getAddressesByName

getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void

Z
zengyawen 已提交
408
使用默认网络解析主机名以获取所有IP地址,使用callback方式作为异步方法。
409 410 411 412 413 414 415

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
416 417 418 419
| 参数名   | 类型                                              | 必填 | 说明               |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| host     | string                                            | 是   | 需要解析的主机名。 |
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | 是   | 回调函数。         |
420 421 422

**示例:**

Z
zengyawen 已提交
423
```js
C
clevercong 已提交
424 425 426 427
let host = "xxxx";
connection.getAddressesByName(host, function (error, addresses) {
    console.log(JSON.stringify(error))
    console.log(JSON.stringify(addresses))
428 429 430 431 432
})
```

## connection.getAddressesByName

C
clevercong 已提交
433
getAddressesByName(host: string): Promise\<Array\<NetAddress>>
434

Z
zengyawen 已提交
435
使用默认网络解析主机名以获取所有IP地址,使用Promise方式作为异步方法。
436 437 438 439 440 441 442

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
443 444 445
| 参数名 | 类型   | 必填 | 说明               |
| ------ | ------ | ---- | ------------------ |
| host   | string | 是   | 需要解析的主机名。 |
446 447 448

**返回值:**

Z
zengyawen 已提交
449 450 451
| 类型                                        | 说明                          |
| ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | 以Promise形式返回所有IP地址。 |
452 453 454

**示例:**

Z
zengyawen 已提交
455
```js
C
clevercong 已提交
456 457 458
let host = "xxxx";
connection.getAddressesByName(host).then(function (addresses) {
    console.log(JSON.stringify(addresses))
459 460 461
})
```

C
clevercong 已提交
462 463 464 465 466 467 468

## connection.enableAirplaneMode

enableAirplaneMode(callback: AsyncCallback\<void>): void

开启飞行模式,使用callback方式作为异步方法。

C
clevercong 已提交
469 470
该接口为系统接口。

C
clevercong 已提交
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

| 参数名   | 类型                                              | 必填 | 说明               |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | 是   | 回调函数。         |

**示例:**

```js
connection.enableAirplaneMode(function (error) {
    console.log(JSON.stringify(error))
})
```

## connection.enableAirplaneMode

enableAirplaneMode(): Promise\<void>

开启飞行模式,使用Promise方式作为异步方法。

C
clevercong 已提交
493 494
该接口为系统接口。

C
clevercong 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
**系统能力**:SystemCapability.Communication.NetManager.Core

**返回值:**

| 类型                                        | 说明                          |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回结果。 |

**示例:**

```js
connection.enableAirplaneMode().then(function (error) {
    console.log(JSON.stringify(error))
})
```


## connection.disableAirplaneMode

disableAirplaneMode(callback: AsyncCallback\<void>): void

关闭飞行模式,使用callback方式作为异步方法。

C
clevercong 已提交
518 519
该接口为系统接口。

C
clevercong 已提交
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

| 参数名   | 类型                                              | 必填 | 说明               |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| callback | AsyncCallback\<void> | 是   | 回调函数。         |

**示例:**

```js
connection.disableAirplaneMode(function (error) {
    console.log(JSON.stringify(error))
})
```

## connection.disableAirplaneMode

disableAirplaneMode(): Promise\<void>

关闭飞行模式,使用Promise方式作为异步方法。

C
clevercong 已提交
542 543
该接口为系统接口。

C
clevercong 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
**系统能力**:SystemCapability.Communication.NetManager.Core

**返回值:**

| 类型                                        | 说明                          |
| ------------------------------------------- | ----------------------------- |
| Promise\<void> | 以Promise形式返回结果。 |

**示例:**

```js
connection.disableAirplaneMode().then(function (error) {
    console.log(JSON.stringify(error))
})
```


561 562 563 564
## connection.createNetConnection

createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection

565
返回一个NetConnection对象,netSpecifier指定关注的网络的各项特征,timeout是超时时间(单位是毫秒),netSpecifier是timeout的必要条件,两者都没有则表示关注默认网络。
566 567 568 569 570

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
571 572 573 574
| 参数名       | 类型                          | 必填 | 说明                                                         |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| netSpecifier | [NetSpecifier](#netspecifier) | 否   | 指定网络的各项特征,不指定则关注默认网络。                   |
| timeout      | number                        | 否   | 获取netSpecifier指定的网络时的超时时间,仅netSpecifier存在时生效。 |
575 576 577

**返回值:**

Z
zengyawen 已提交
578 579 580
| 类型                            | 说明                 |
| ------------------------------- | -------------------- |
| [NetConnection](#netconnection) | 所关注的网络的句柄。 |
581 582 583

**示例:**

Z
zengyawen 已提交
584
```js
585
// 关注默认网络
C
clevercong 已提交
586
let netConnection = connection.createNetConnection()
587 588

// 关注蜂窝网络
C
clevercong 已提交
589
let netConnectionCellular = connection.createNetConnection({
590
    netCapabilities: {
C
clevercong 已提交
591
        bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
592 593 594 595
    }
})
```

M
maosiping 已提交
596
## NetConnection
597

Z
zengyawen 已提交
598
网络连接的句柄。
599

M
maosiping 已提交
600
### on('netAvailable')
601 602 603

on(type: 'netAvailable', callback: Callback\<NetHandle>): void

C
clevercong 已提交
604
订阅网络可用事件。
605 606 607 608 609

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
610 611
| 参数名   | 类型                               | 必填 | 说明                                                         |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
C
clevercong 已提交
612
| type     | string                             | 是   | 订阅事件,固定为'netAvailable'。<br>netAvailable:数据网络可用事件。 |
Z
zengyawen 已提交
613
| callback | Callback\<[NetHandle](#nethandle)> | 是   | 回调函数。                                                   |
614 615 616

**示例:**

Z
zengyawen 已提交
617
```js
C
clevercong 已提交
618
netConnection.on('netAvailable', function (data) {
619 620 621 622
    console.log(JSON.stringify(data))
})
```

M
maosiping 已提交
623
### on('netCapabilitiesChange')
624 625 626

on(type: 'netCapabilitiesChange', callback: Callback<{ netHandle: NetHandle, netCap: NetCapabilities }>): void

C
clevercong 已提交
627
订阅网络能力变化事件。
628 629 630 631 632

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
633 634
| 参数名   | 类型                                                         | 必填 | 说明                                                         |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
C
clevercong 已提交
635
| type     | string                                                       | 是   | 订阅事件,固定为'netCapabilitiesChange'。<br/>netCapabilitiesChange:网络能力变化事件。 |
Z
zengyawen 已提交
636
| callback | Callback<{ netHandle: [NetHandle](#nethandle), netCap: [NetCapabilities](#netcapabilities) }> | 是   | 回调函数。                                                   |
637 638 639

**示例:**

Z
zengyawen 已提交
640
```js
C
clevercong 已提交
641
netConnection.on('netCapabilitiesChange', function (data) {
642 643 644 645
    console.log(JSON.stringify(data))
})
```

M
maosiping 已提交
646
### on('netConnectionPropertiesChange')
647 648 649

on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void

C
clevercong 已提交
650
订阅网络连接信息变化事件。
651 652 653 654 655

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
656 657
| 参数名   | 类型                                                         | 必填 | 说明                                                         |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
C
clevercong 已提交
658
| type     | string                                                       | 是   | 订阅事件,固定为'netConnectionPropertiesChange'。<br/>netConnectionPropertiesChange:网络连接信息变化事件。 |
Z
zengyawen 已提交
659
| callback | Callback<{ netHandle: [NetHandle](#nethandle), connectionProperties: [ConnectionProperties](#connectionproperties) }> | 是   | 回调函数。                                                   |
660 661 662

**示例:**

Z
zengyawen 已提交
663
```js
C
clevercong 已提交
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
netConnection.on('netConnectionPropertiesChange', function (data) {
    console.log(JSON.stringify(data))
})
```

### on('netBlockStatusChange')

on(type: 'netBlockStatusChange', callback: Callback&lt;{ netHandle: NetHandle, blocked: boolean }&gt;): void

订阅网络阻塞状态事件,使用callback方式作为异步方法。

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

| 参数名   | 类型                                                         | 必填 | 说明                                                         |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| type     | string                                                       | 是   | 订阅事件,固定为'netBlockStatusChange'。<br/>netBlockStatusChange:网络阻塞状态事件。 |
| callback | Callback&lt;{&nbsp;netHandle:&nbsp;[NetHandle](#nethandle),&nbsp;blocked:&nbsp;boolean&nbsp;}&gt; | 是   | 回调函数。                                                   |

**示例:**

Z
zengyawen 已提交
686
```js
C
clevercong 已提交
687
netConnection.on('netBlockStatusChange', function (data) {
688 689 690 691
    console.log(JSON.stringify(data))
})
```

M
maosiping 已提交
692
### on('netLost')
693 694 695

on(type: 'netLost', callback: Callback\<NetHandle>): void

C
clevercong 已提交
696
订阅网络丢失事件。
697 698 699 700 701

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
702 703
| 参数名   | 类型                               | 必填 | 说明                                                         |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
C
clevercong 已提交
704
| type     | string                             | 是   | 订阅事件,固定为'netLost'。<br/>netLost:网络严重中断或正常断开事件。 |
Z
zengyawen 已提交
705
| callback | Callback\<[NetHandle](#nethandle)> | 是   | 回调函数。                                                   |
706 707 708

**示例:**

Z
zengyawen 已提交
709
```js
C
clevercong 已提交
710 711
let netConnection1 = connection.createNetConnection()
netConnection1.on('netLost', function (data) {
712 713 714 715
    console.log(JSON.stringify(data))
})
```

M
maosiping 已提交
716
### on('netUnavailable')
717 718 719

on(type: 'netUnavailable', callback: Callback\<void>): void

C
clevercong 已提交
720
订阅网络不可用事件。
721 722 723 724 725

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
726 727
| 参数名   | 类型            | 必填 | 说明                                                         |
| -------- | --------------- | ---- | ------------------------------------------------------------ |
C
clevercong 已提交
728
| type     | string          | 是   | 订阅事件,固定为'netUnavailable'。<br/>netUnavailable:网络不可用事件。 |
Z
zengyawen 已提交
729
| callback | Callback\<void> | 是   | 回调函数。                                                   |
730 731 732

**示例:**

Z
zengyawen 已提交
733
```js
C
clevercong 已提交
734
netConnection.on('netUnavailable', function (data) {
735 736 737 738
    console.log(JSON.stringify(data))
})
```

M
maosiping 已提交
739
### register
740 741 742

register(callback: AsyncCallback\<void>): void

C
clevercong 已提交
743
订阅指定网络状态变化的通知。
744 745 746 747 748 749 750

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
751 752 753
| 参数名   | 类型                 | 必填 | 说明       |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是   | 回调函数。 |
754 755 756

**示例:**

Z
zengyawen 已提交
757
```js
C
clevercong 已提交
758
netConnection.register(function (error) {
759 760 761 762
    console.log(JSON.stringify(error))
})
```

M
maosiping 已提交
763
### unregister
764 765 766

unregister(callback: AsyncCallback\<void>): void

C
clevercong 已提交
767
取消订阅默认网络状态变化的通知。
768 769 770 771 772

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
773 774 775
| 参数名   | 类型                 | 必填 | 说明       |
| -------- | -------------------- | ---- | ---------- |
| callback | AsyncCallback\<void> | 是   | 回调函数。 |
776 777 778

**示例:**

Z
zengyawen 已提交
779
```js
C
clevercong 已提交
780
netConnection.unregister(function (error) {
781 782 783 784
    console.log(JSON.stringify(error))
})
```

M
maosiping 已提交
785
## NetHandle
786

Z
zengyawen 已提交
787
数据网络的句柄。
788

Z
zengyawen 已提交
789 790
在调用NetHandle的方法之前,需要先获取NetHandle对象。

C
clevercong 已提交
791 792
**系统能力**:SystemCapability.Communication.NetManager.Core

Z
zengyawen 已提交
793 794
### 属性

C
clevercong 已提交
795 796 797
| 参数名 | 类型   | 说明                      |
| ------ | ------ | ------------------------- |
| netId  | number | 网络ID,必须大于等于100。 |
798

Z
zhuwenchao 已提交
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900

### bindSocket

bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void;

将TCPSocket或UDPSocket绑定到当前网络,使用callback方式作为异步方法。

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

| 参数名      | 类型                     | 必填 | 说明                            |
| ----------- | ------------------------ | ---- | -------------------------------|
| socketParam | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | 是 | 待绑定的TCPSocket或UDPSocket对象。|
| callback    | AsyncCallback\<void>      | 是   | 回调函数                        |

**示例:**

```js
connection.getDefaultNet().then(function (netHandle) {
    var tcp = socket.constructTCPSocketInstance();
    var udp = socket.constructUDPSocketInstance();
    let socketType = "xxxx";
    if (socketType == "TCPSocket") {
        tcp.bind({
            address: "xxxx", port: xxxx, family: xxxx
        }, err => {
            netHandle.bindSocket(tcp, function (error, data) {
            console.log(JSON.stringify(error))
            console.log(JSON.stringify(data))
        })
    } else {
        udp.on('message', callback);
        udp.bind({
            address: "xxxx", port: xxxx, family: xxxx
        }, err => {
            udp.on('message', (data) => {
            console.log(JSON.stringify(data))
            });
            netHandle.bindSocket(udp, function (error, data) {
            console.log(JSON.stringify(error))
            console.log(JSON.stringify(data))
            });
        })
     }
}
```

### bindSocket

bindSocket(socketParam: TCPSocket \| UDPSocket): Promise\<void>;

将TCPSocket或UDPSockett绑定到当前网络,使用Promise方式作为异步方法。

**需要权限**:ohos.permission.GET_NETWORK_INFO

**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

| 参数名          | 类型                  | 必填  | 说明                           |
| --------------- | --------------------- | ---- | ------------------------------ |
| socketParam     | [TCPSocket](js-apis-socket.md#tcpsocket) \| [UDPSocket](js-apis-socket.md#udpsocket) | 是   | 待绑定的TCPSocket或UDPSocket对象。|

**返回值:**

| 类型           | 说明                   |
| -------------- | ---------------------- |
| Promise\<void> | 以Promise形式返回结果。 |

**示例:**

```js
connection.getDefaultNet().then(function (netHandle) {
    var tcp = socket.constructTCPSocketInstance();
    var udp = socket.constructUDPSocketInstance();
    let socketType = "xxxx";
    if(socketType == "TCPSocket") {
        tcp.bind({
            address: "xxxx", port: xxxx, family: xxxx
        }, err => {
            netHandle.bindSocket(tcp).then(err, data) {
            console.log(JSON.stringify(data))
        })
    } else {
        udp.on('message', callback);
        udp.bind({
            address: "xxxx", port: xxxx, family: xxxx
        }, err => {
            udp.on('message', (data) => {
            console.log(JSON.stringify(data))
            });
            netHandle.bindSocket(tcp).then(err, data) {
            console.log(JSON.stringify(data))
            });
        })
     }
}
```

M
maosiping 已提交
901
### getAddressesByName
902 903 904

getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>): void

Z
zengyawen 已提交
905
使用对应网络解析主机名以获取所有IP地址,使用callback方式作为异步方法。
906

C
clevercong 已提交
907 908
**需要权限**:ohos.permission.GET_NETWORK_INFO

909 910 911 912
**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
913 914 915 916
| 参数名   | 类型                                              | 必填 | 说明               |
| -------- | ------------------------------------------------- | ---- | ------------------ |
| host     | string                                            | 是   | 需要解析的主机名。 |
| callback | AsyncCallback\<Array\<[NetAddress](#netaddress)>> | 是   | 回调函数           |
917 918 919

**示例:**

Z
zengyawen 已提交
920
```js
921
connection.getDefaultNet().then(function (netHandle) {
C
clevercong 已提交
922 923
    let host = "xxxx";
    netHandle.getAddressesByName(host, function (error, addresses) {
924
        console.log(JSON.stringify(error))
C
clevercong 已提交
925
        console.log(JSON.stringify(addresses))
926 927 928 929
    })
})
```

M
maosiping 已提交
930
### getAddressesByName
931

C
clevercong 已提交
932
getAddressesByName(host: string): Promise\<Array\<NetAddress>>
933

Z
zengyawen 已提交
934
使用对应网络解析主机名以获取所有IP地址,使用Promise方式作为异步方法。
935

C
clevercong 已提交
936 937
**需要权限**:ohos.permission.GET_NETWORK_INFO

938 939 940 941
**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
942 943 944
| 参数名 | 类型   | 必填 | 说明               |
| ------ | ------ | ---- | ------------------ |
| host   | string | 是   | 需要解析的主机名。 |
945 946 947

**返回值:**

Z
zengyawen 已提交
948 949 950
| 类型                                        | 说明                          |
| ------------------------------------------- | ----------------------------- |
| Promise\<Array\<[NetAddress](#netaddress)>> | 以Promise形式返回所有IP地址。 |
951 952 953

**示例:**

Z
zengyawen 已提交
954
```js
955
connection.getDefaultNet().then(function (netHandle) {
C
clevercong 已提交
956 957 958
    let host = "xxxx";
    netHandle.getAddressesByName(host).then(function (addresses) {
        console.log(JSON.stringify(addresses))
959 960 961 962
    })
})
```

M
maosiping 已提交
963
### getAddressByName
964 965 966

getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void

Z
zengyawen 已提交
967
使用对应网络解析主机名以获取第一个IP地址,使用callback方式作为异步方法。
968

C
clevercong 已提交
969 970
**需要权限**:ohos.permission.GET_NETWORK_INFO

971 972 973 974
**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
975 976 977 978
| 参数名   | 类型                                      | 必填 | 说明               |
| -------- | ----------------------------------------- | ---- | ------------------ |
| host     | string                                    | 是   | 需要解析的主机名。 |
| callback | AsyncCallback\<[NetAddress](#netaddress)> | 是   | 回调函数。         |
979 980 981

**示例:**

Z
zengyawen 已提交
982
```js
983
connection.getDefaultNet().then(function (netHandle) {
C
clevercong 已提交
984 985
    let host = "xxxx";
    netHandle.getAddressByName(host, function (error, address) {
986
        console.log(JSON.stringify(error))
C
clevercong 已提交
987
        console.log(JSON.stringify(address))
988 989 990 991
    })
})
```

M
maosiping 已提交
992
### getAddressByName
993

C
clevercong 已提交
994
getAddressByName(host: string): Promise\<NetAddress>
995

Z
zengyawen 已提交
996
使用对应网络解析主机名以获取第一个IP地址,使用Promise方式作为异步方法。
997

C
clevercong 已提交
998 999
**需要权限**:ohos.permission.GET_NETWORK_INFO

1000 1001 1002 1003
**系统能力**:SystemCapability.Communication.NetManager.Core

**参数:**

Z
zengyawen 已提交
1004 1005 1006
| 参数名 | 类型   | 必填 | 说明               |
| ------ | ------ | ---- | ------------------ |
| host   | string | 是   | 需要解析的主机名。 |
1007 1008 1009

**返回值:**

Z
zengyawen 已提交
1010 1011 1012
| 类型                                | 说明                            |
| ----------------------------------- | ------------------------------- |
| Promise\<[NetAddress](#netaddress)> | 以Promise形式返回第一个IP地址。 |
1013 1014 1015

**示例:**

Z
zengyawen 已提交
1016
```js
1017
connection.getDefaultNet().then(function (netHandle) {
C
clevercong 已提交
1018 1019 1020
    let host = "xxxx";
    netHandle.getAddressByName(host).then(function (address) {
        console.log(JSON.stringify(address))
1021 1022 1023 1024
    })
})
```

M
maosiping 已提交
1025
## NetSpecifier
1026

Z
zengyawen 已提交
1027
提供承载数据网络能力的实例。
1028

C
clevercong 已提交
1029 1030 1031
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。

| 参数名                  | 类型                                | 说明                                                         |
Z
zengyawen 已提交
1032 1033 1034
| ----------------------- | ----------------------------------- | ------------------------------------------------------------ |
| netCapabilities         | [NetCapabilities](#netcapabilities) | 存储数据网络的传输能力和承载类型。                           |
| bearerPrivateIdentifier | string                              | 网络标识符,WIFI网络的标识符是"wifi",蜂窝网络的标识符是"slot0"(对应SIM卡1)。 |
1035

M
maosiping 已提交
1036
## NetCapabilities
1037

M
maosiping 已提交
1038
网络的能力集。
1039

C
clevercong 已提交
1040 1041 1042
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。

| 参数名                | 类型                               | 说明                     |
Z
zengyawen 已提交
1043 1044 1045 1046
| --------------------- | ---------------------------------- | ------------------------ |
| linkUpBandwidthKbps   | number                             | 上行(设备到网络)带宽。 |
| linkDownBandwidthKbps | number                             | 下行(网络到设备)带宽。 |
| networkCap            | Array<[NetCap](#netcap)>           | 网络具体能力。           |
Z
zengyawen 已提交
1047
| bearerTypes           | Array<[NetBearType](#netbeartype)> | 网络类型。               |
1048

M
maosiping 已提交
1049
## NetCap
1050

M
maosiping 已提交
1051
网络具体能力。
1052

C
clevercong 已提交
1053 1054 1055
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。

| 参数名                  | 值   | 说明                   |
Z
zengyawen 已提交
1056
| ------------------------ | ---- | ---------------------- |
C
clevercong 已提交
1057 1058
| NET_CAPABILITY_MMS | 0 | 表示网络可以访问运营商的MMSC(Multimedia&nbsp;Message&nbsp;Service,多媒体短信服务)发送和接收彩信。 |
| NET_CAPABILITY_NOT_METERED | 11 | 表示网络流量未被计费。 |
1059
| NET_CAPABILITY_INTERNET  | 12   | 表示该网络应具有访问Internet的能力,该能力由网络提供者设置。 |
C
clevercong 已提交
1060
| NET_CAPABILITY_NOT_VPN | 15 | 表示网络不使用VPN(Virtual&nbsp;Private&nbsp;Network,虚拟专用网络)。 |
1061
| NET_CAPABILITY_VALIDATED | 16   | 表示该网络访问Internet的能力被网络管理成功验证,该能力由网络管理模块设置。 |
1062

M
maosiping 已提交
1063
## NetBearType
1064

M
maosiping 已提交
1065
网络类型。
1066

C
clevercong 已提交
1067 1068 1069
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。

| 名称         | 值   | 说明        |
Z
zengyawen 已提交
1070 1071 1072
| --------------- | ---- | ----------- |
| BEARER_CELLULAR | 0    | 蜂窝网络。  |
| BEARER_WIFI     | 1    | Wi-Fi网络。 |
C
clevercong 已提交
1073
| BEARER_ETHERNET | 3 | 以太网网络。 |
1074

M
maosiping 已提交
1075
## ConnectionProperties
1076

M
maosiping 已提交
1077
网络连接信息。
1078

C
clevercong 已提交
1079 1080 1081
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。

| 参数名       | 类型                               | 说明             |
Z
zengyawen 已提交
1082 1083 1084 1085 1086
| ------------- | ---------------------------------- | ---------------- |
| interfaceName | string                             | 网卡名称。       |
| domains       | string                             | 所属域,默认""。 |
| linkAddresses | Array<[LinkAddress](#linkaddress)> | 链路信息。       |
| routes        | Array<[RouteInfo](#routeinfo)>     | 路由信息。       |
C
clevercong 已提交
1087
| dnses | Array&lt;[NetAddress](#netaddress)&gt; | 网络地址,参考[NetAddress](#netaddress)。 |
Z
zengyawen 已提交
1088
| mtu           | number                             | 最大传输单元。   |
1089

M
maosiping 已提交
1090
## LinkAddress
1091

M
maosiping 已提交
1092
网络链路信息。
1093

C
clevercong 已提交
1094 1095 1096
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。

| 参数名       | 类型                      | 说明                 |
Z
zengyawen 已提交
1097 1098 1099
| ------------ | ------------------------- | -------------------- |
| address      | [NetAddress](#netaddress) | 链路地址。           |
| prefixLength | number                    | 链路地址前缀的长度。 |
1100

M
maosiping 已提交
1101
## RouteInfo
1102

M
maosiping 已提交
1103
网络路由信息。
1104

C
clevercong 已提交
1105 1106 1107
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。

| 参数名         | 类型                        | 说明             |
Z
zengyawen 已提交
1108 1109 1110 1111 1112 1113
| -------------- | --------------------------- | ---------------- |
| interface      | string                      | 网卡名称。       |
| destination    | [LinkAddress](#linkaddress) | 目的地址。       |
| gateway        | [NetAddress](#netaddress)   | 网关地址。       |
| hasGateway     | boolean                     | 是否有网关。     |
| isDefaultRoute | boolean                     | 是否为默认路由。 |
1114

M
maosiping 已提交
1115
## NetAddress
1116

Z
zengyawen 已提交
1117
网络地址。
1118

C
clevercong 已提交
1119 1120 1121
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.NetManager.Core。

| 参数名  | 类型   | 说明                           |
Z
zengyawen 已提交
1122 1123 1124
| ------- | ------ | ------------------------------ |
| address | string | 地址。                         |
| family  | number | IPv4 = 1,IPv6 = 2,默认IPv4。 |
Z
zhuwenchao 已提交
1125
| port    | number | 端口,取值范围\[0, 65535]。    |