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