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 { 52 getType() { 53 network.getType({ 54 success: function(data) { 55 console.log('success get network type:' + data.type); 56 }, 57 fail: function(data, code) { 58 console.log('fail to get network type code:' + code + ', data:' + data); 59 }, 60 }); 61 }, 62} 63``` 64 65 66## network.subscribe<sup>3+</sup> 67 68subscribe(options?:{<br> 69 success?: (data: NetworkResponse) => void;<br> 70 fail?: (data: any, code: number) => void;<br> 71 }): void 72 73订阅当前设备的网络连接状态。如果多次调用,会覆盖前一次调用。 74 75**系统能力:** SystemCapability.Communication.NetManager.Core 76 77**参数:** 78 79| 参数名 | 类型 | 必填 | 说明 | 80| -------- | -------- | -------- | -------- | 81| success | Function | 否 | 网络发生变化的回调函数,返回值为[NetworkResponse](#networkresponse3) | 82| fail | Function | 否 | 接口调用失败的回调函数。 | 83 84fail返回值: 85 86| 错误码 | 说明 | 87| -------- | -------- | 88| 602 | 当前权限未声明。 | 89| 200 | 订阅失败。 | 90 91**示例:** 92 93``` 94export default { 95 subscribe() { 96 network.subscribe({ 97 success: function(data) { 98 console.log('network type change type:' + data.type); 99 }, 100 fail: function(data, code) { 101 console.log('fail to subscribe network, code:' + code + ', data:' + data); 102 }, 103 }); 104 }, 105} 106``` 107 108 109## network.unsubscribe<sup>3+</sup> 110 111unsubscribe(): void 112 113取消订阅设备的网络连接状态。 114 115**系统能力:** SystemCapability.Communication.NetManager.Core 116 117**示例:** 118 119``` 120export default { 121 unsubscribe() { 122 network.unsubscribe(); 123 }, 124} 125``` 126 127 128## NetworkResponse<sup>3+</sup> 129 130**系统能力:** SystemCapability.Communication.NetManager.Core 131 132| 名称 | 类型 | 必填 | 说明 | 133| -------- | -------- | -------- | -------- | 134| metered | boolean | 否 |是否按照流量计费。 | 135| type | string | 是|网络类型,可能的值有2g,3g,4g,5g,wifi,none等。 | 136