1# @system.network (网络状态) 2 3> **说明:** 4> - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 5 6 7## 导入模块 8 9 10``` 11import network from '@system.network'; 12``` 13 14 15## 权限列表 16 17ohos.permission.GET_WIFI_INFO 18 19ohos.permission.GET_NETWORK_INFO 20 21 22## network.getType<sup>3+</sup> 23 24getType(options?: {<br> 25 success?: (data: NetworkResponse) => void;<br> 26 fail?: (data: any, code: number) => void;<br> 27 complete?: () => void;<br> 28}): void 29 30获取当前设备的网络类型。 31 32**系统能力:** SystemCapability.Communication.NetManager.Core 33 34**参数:** 35 36| 参数名 | 类型 | 必填 | 说明 | 37| -------- | -------- | -------- | -------- | 38| success | Function | 否 | 接口调用成功的回调函数,返回值为[NetworkResponse](#networkresponse3) | 39| fail | Function | 否 | 接口调用失败的回调函数。 | 40| complete | Function | 否 | 接口调用结束的回调函数。 | 41 42fail返回值: 43 44| 错误码 | 说明 | 45| -------- | -------- | 46| 602 | 当前权限未声明。 | 47 48**示例:** 49 50``` 51export default class Network { 52 getType() { 53 network.getType({ 54 success: (data) => { 55 console.log('success get network type:' + data.type); 56 } 57 }); 58 } 59} 60``` 61 62 63## network.subscribe<sup>3+</sup> 64 65subscribe(options?:{<br> 66 success?: (data: NetworkResponse) => void;<br> 67 fail?: (data: any, code: number) => void;<br> 68 }): void 69 70订阅当前设备的网络连接状态。如果多次调用,会覆盖前一次调用。 71 72**系统能力:** SystemCapability.Communication.NetManager.Core 73 74**参数:** 75 76| 参数名 | 类型 | 必填 | 说明 | 77| -------- | -------- | -------- | -------- | 78| success | Function | 否 | 网络发生变化的回调函数,返回值为[NetworkResponse](#networkresponse3) | 79| fail | Function | 否 | 接口调用失败的回调函数。 | 80 81fail返回值: 82 83| 错误码 | 说明 | 84| -------- | -------- | 85| 602 | 当前权限未声明。 | 86| 200 | 订阅失败。 | 87 88**示例:** 89 90``` 91export default class Network { 92 subscribe() { 93 network.subscribe({ 94 success: (data) => { 95 console.log('success get network type:' + data.type); 96 } 97 }); 98 } 99} 100``` 101 102 103## network.unsubscribe<sup>3+</sup> 104 105unsubscribe(): void 106 107取消订阅设备的网络连接状态。 108 109**系统能力:** SystemCapability.Communication.NetManager.Core 110 111**示例:** 112 113``` 114export default { 115 unsubscribe() { 116 network.unsubscribe(); 117 }, 118} 119``` 120 121 122## NetworkResponse<sup>3+</sup> 123 124**系统能力:** SystemCapability.Communication.NetManager.Core 125 126| 名称 | 类型 | 必填 | 说明 | 127| -------- | -------- | -------- | -------- | 128| metered | boolean | 否 |是否按照流量计费。 | 129| type | string | 是|网络类型,可能的值有2g,3g,4g,5g,wifi,none等。 | 130