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