Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Netinfo.isConnected always returns true in Android

i am using react-native-netinfo in my app. In iOS it's working fine. But in android always returns true. It doesn't have internet connection (WiFi or Mobile data). It still returns true. Please give me any suggestions.

Versions:-

react-native:- 0.61.4,
@react-native-community/netinfo:- 4.6.1

Here is my code:-

  componentDidMount() {
    NetInfo.isConnected.addEventListener(
      'connectionChange',
      this.handleConnectivityChange,
    );
  }
  handleConnectivityChange = isConnected => {
    console.log('uyeuiyiuyiu', isConnected);
    this.setState({
      connectionStatus: isConnected,
    });
  };
  componentWillUnmount() {
    NetInfo.isConnected.removeEventListener(
      'connectionChange',
      this.handleConnectivityChange,
    );
  }
like image 636
Harika Avatar asked Oct 16 '25 23:10

Harika


1 Answers

you use the new library, but the API you use is Deprecated. you can see this in this link.

for android, you have to add the internet permission at the android native AndroidMainFest.xml

// the app can link the network
<uses-permission
        android:name="android.permission.INTERNET" />
// get the network state
<uses-permission
        android:name="android.permission.ACCESS_NETWORK_STATE" />
// get the wifi state
    <uses-permission
        android:name="android.permission.ACCESS_WIFI_STATE" />

if you want to know the network is connected, you can use the following code

NetInfo.fetch().then(state => {
  if(state. isConnected){
   }
});

if you want to know when user change the network, whether it is connected, you can use the following code

 NetInfo.addEventListener(state => {
 if(state. isConnected){
   }
});

like image 90
Lenoarod Avatar answered Oct 18 '25 14:10

Lenoarod



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!