NetInfo 获取网络情况

NetInfo 获取网络情况

版本

"react-native": "0.62.2",
"@react-native-community/netinfo": "5.9.10",

使用

import NetInfo from '@react-native-community/netinfo';
//主动获取
  NetInfo.fetch().then(state => {
    console.log('网络类型', state.type);
    console.log('是否连接', state.isConnected);
    console.log('是否可以访问互联网', state.isInternetReachable);
    console.log('strength', state.details.strength);
  });
  //网络发生变化
  this.unsubscribe && this.unsubscribe(); 
  this.unsubscribe = NetInfo.addEventListener(async state => {
    console.log('网络变化', state);
    let Strength =await  NativeModules.OpenNativeModule.getSignalStrength();
    console.log(Strength, "信号强度")
  });

获取到的样例

// {"details": {"carrier": "CHINA MOBILE", "cellularGeneration": "4g", "isConnectionExpensive": true}, "isConnected": true, "isInternetReachable": true, "isWifiEnabled": false, "type": "cellular"}
  // {"details": {"bssid": "08:5c:1b:ac:d1:00", "frequency": 2462, "isConnectionExpensive": false, "ssid": "wifi名字", "strength": 83}, "isConnected": true, "isInternetReachable": true, "isWifiEnabled": true, "type": "wifi"}
  // {"details": {}, "isConnected": false, "isInternetReachable": false, "isWifiEnabled": false, "type": "none"}
  // {"details": {"isConnectionExpensive": false}, "isConnected": true, "isInternetReachable": true, "isWifiEnabled": true, "type": "ethernet"}

Android代码获取信号强度

@RequiresPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
    @ReactMethod
    public void getSignalStrength(Promise promise) {
        try {
            ConnectivityManager cm = (ConnectivityManager) getReactApplicationContext()
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            if (activeNetwork == null){
                WritableMap map = Arguments.createMap();
                map.putInt("dbm", 0);
                map.putInt("level", 0);
                map.putString("networkType", "DISCONNECTED");
                promise.resolve(map);
                return;
            }
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                // 如果没有获取到LTE信号,尝试获取WiFi信号
                WifiManager wifiManager = (WifiManager) mReactContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int rssi = wifiInfo.getRssi();
                // 将 RSSI 转换为 0~4 的等级
                int level = WifiManager.calculateSignalLevel(rssi, 5); // 5 表示分为 5 级(0~4)
                WritableMap map = Arguments.createMap();
                map.putInt("dbm", rssi);
                map.putInt("level", level);
                map.putString("networkType", "WiFi");
                promise.resolve(map);
                return;
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                TelephonyManager telephonyManager = (TelephonyManager) mReactContext.getSystemService(Context.TELEPHONY_SERVICE);
                List<CellInfo> cellInfos = telephonyManager.getAllCellInfo();

                if (cellInfos != null) {
                    for (CellInfo cellInfo : cellInfos) {
                        if (cellInfo instanceof CellInfoLte) {
                            CellSignalStrengthLte signalStrength = ((CellInfoLte) cellInfo).getCellSignalStrength();
                            int dbm ;
                            try {
                                dbm = signalStrength.getDbm();
                                Log.d(TAG, "getSignalStrengthdbm2: "+dbm);
                                if (dbm>0) {
    //                                正确转换 ASU 为 dBm
                                    int asu = signalStrength.getAsuLevel();
                                    Log.d(TAG, "getSignalStrengthasu: " + asu);
                                    dbm = -113 + (2 * asu);
                                    if (dbm > 0) dbm = -Math.abs(dbm); // 二次保护
                                }
                            }catch (Exception e) {
                                dbm = -100; // 默认值
                            }


//
                            int level = signalStrength.getLevel();  // 0: 无信号, 4: 满格
                            WritableMap map = Arguments.createMap();
                            map.putInt("dbm", dbm);
                            map.putInt("level", level);
                            map.putString("networkType", "Cellular");
                            promise.resolve(map);
                            return;
                        }
                    }
                }
                WritableMap map = Arguments.createMap();
                map.putInt("dbm", -100);
                map.putInt("level", 0);
                map.putString("networkType", "Cellular");
                promise.resolve(map);
            }else if (activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET) {
                WritableMap map = Arguments.createMap();
                map.putInt("dbm", 0);
                map.putInt("level", 0);
                map.putString("networkType", "Ethernet");
                promise.resolve(map);
            }else {
                WritableMap map = Arguments.createMap();
                map.putInt("dbm", 0);
                map.putInt("level", 0);
                map.putString("networkType", "OTHER");
                promise.resolve(map);
            }






        } catch (Exception e) {
            promise.reject("ERROR", "Failed to get signal strength", e);
        }
    }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值