AlexVPerl
AlexVPerl

Reputation: 7996

Android Network Check Unreliable

It seems that I'm facing an issue where the network check isnt reliable. What I mean by that is that it sometimes returns true when actually network isn't available.

This happens in real world scenarios when you go underground and loose signal, the phone properly reports it showing no bars but the check will still return true.

I'm using the following code:

    ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);    
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); 
    boolean isNetworkAvailalbe = (activeNetworkInfo != null);

I'm looking for the most bullet proof way to implement a reliable network check, any recommendations ?

Upvotes: 1

Views: 494

Answers (2)

Sandro Machado
Sandro Machado

Reputation: 10205

ConnectivityManager cm =
    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                      activeNetwork.isConnectedOrConnecting();

On the Android Developer portal you can find more information: http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html

Upvotes: 1

Vishal Khakhkhar
Vishal Khakhkhar

Reputation: 2116

try with this..

public static boolean checkNetworkRechability(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        isInternetAvailable();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    public static boolean isInternetAvailable() {
        Log.i("TAG", "isInternetAvailable start");
        try {
            InetAddress ipAddr = InetAddress.getByName(new URL("google.com").getHost());


            String ip = ipAddr.getHostAddress();
            if (ip.equals("")) {
                return false;
            } else {
                Log.i("TAG", "IP Address : " + ip);
                return true;
            }

        } catch (Exception e) {
            return false;
        }

    }

Upvotes: 1

Related Questions