React Native之NetInfo获取网络连接信息

1,061 阅读1分钟

通过 NetInfo 模块可以获取设备当前的联网状态。

NetInfo.getConnectionInfo().then((connectionInfo) => {
  console.log('Initial, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
});
function handleFirstConnectivityChange(connectionInfo) {
  console.log('First change, type: ' + connectionInfo.type + ', effectiveType: ' + connectionInfo.effectiveType);
  NetInfo.removeEventListener(
    'connectionChange',
    handleFirstConnectivityChange
  );
}
NetInfo.addEventListener(
  'connectionChange',
  handleFirstConnectivityChange
);

ConnectionType 枚举值

ConnectionType描述了设备联网的方式。

ConnectionType有如下跨平台可用的值:

  • none - 设备处于离线状态
  • wifi - 设备通过 wifi 联网,或者设备是 iOS 模拟器
  • cellular - 设备通过蜂窝数据流量联网
  • unknown - 联网状态异常

ConnectionType还有如下仅在 Android 平台上可用的值:

  • bluetooth - 设备通过蓝牙协议联网
  • ethernet - 设备通过以太网协议联网
  • wimax - 设备通过 WiMAX 协议联网

EffectiveConnectionType 枚举值

EffectiveConnectionType有如下跨平台可用的值:

  • 2g
  • 3g
  • 4g
  • unknown

Android

要在 Android 上获取联网状态,还需要在AndroidManifest.xml中添加如下权限请求: <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

方法

addEventListener()

添加一个事件监听函数

NetInfo.addEventListener(status => {
    console.log('Status:' + JSON.stringify(status));
    if (this.status) {
        /// 网络先线下,
        if (this.status.isConnected === false) {
            /// 网络后在线上
            if (status && (status.isConnected === true)) {
                /// 发送通知
                this.status = status;
                DeviceEventEmitter.emit('NetworkOnLine');
                this.online && this.online(status)
            }
        }
    }
    this.stateChange && this.stateChange(status)
    if (status && (status.isConnected !== true)) {
        this.offline && this.offline(status)
    }
    this.status = status;
    console.log('网络连接信息----------', this.status)
});
//网络是否连接的监听
NetInfo.fetch().then(state => {
    console.log('Connection type', state.type);
    console.log('Is connected?', state.isConnected);
});

getConnectionInfo()

NetInfo.getConnectionInfo();

返回一个 promise,最终解析值为带有typeeffectiveType属性的对象。其中type属性的值为ConnectionType ,而effectiveType属性的值为EffectiveConnectionType。

属性

isConnected

以异步方式获取一个布尔值,用于判断当前设备是否联网。

NetInfo.isConnected.fetch().then(isConnected => {
  console.log('First, is ' + (isConnected ? 'online' : 'offline'));
});
function handleFirstConnectivityChange(isConnected) {
  console.log('Then, is ' + (isConnected ? 'online' : 'offline'));
  NetInfo.isConnected.removeEventListener(
    'connectionChange',
    handleFirstConnectivityChange
  );
}
NetInfo.isConnected.addEventListener(
  'connectionChange',
  handleFirstConnectivityChange
);