Search code examples
javaandroidandroid-wifiwifimanager

Check the stable Internet


My application uses the getInet4AddressByName () method. It needs the Internet turned on. To check the Wi-Fi status, I use the BroadcastReceiver receiver. But a stable Internet appears after some time after turning on Wi-Fi and the method does not have time to work correctly getInet4AddressByName() returns an error. How can I track the presence of a stable Internet connection rather than the wi-fi connection? Thanks.

@Override
public void onReceive(Context context, Intent intent) {
 WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
 if (wifi.isWifiEnabled()) {
   tv.setText("You are connected");
 } else {
   tv.setText("You are NOT connected");
 }
}
};

Solution

  • You can use two method :

    Google recommends this code block for checking internet connection. Because the device may have not internet connection even if it is connected to WiFi. 1 - for check connection :

     private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }
    

    2 - for check internet :

      public boolean internetIsConnected() {
        try {
            String command = "ping -c 1 google.com";
            return (Runtime.getRuntime().exec(command).waitFor() == 0);
        } catch (Exception e) {
            return false;
        }
    }
    

    Add permissions to manifest :

     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />