Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem in detecting Internet Connection in Android

Tags:

android

I have created a Android application using Google Maps. Now I want to check whether an internet connection is available or not. I search in Google and finally I got solution through Stackoverflow:

boolean HaveConnectedWifi = false;
boolean HaveConnectedMobile = false;
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo)
    {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
            if (ni.isConnected())
                HaveConnectedWifi = true;
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
            if (ni.isConnected())
                HaveConnectedMobile = true;
    }
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />   

I have written my online Google map code if it return true and offline code if it return false.

My problem is its showing an internet connection is available even when it is not. Where have I made a mistake?

like image 734
deepa Avatar asked Dec 16 '22 12:12

deepa


1 Answers

Try using NetworkInfo ni = cm.getActiveNetworkInfo(); instead of NetworkInfo ni = cm.getAllNetworkInfo();. There should only be one active data network at any one time because Android will use the best available and shut down the others to conserve battery.

Also, I tend to use ni.isConnectedOrConnecting(); instead of ni.isConnected(); because it can catch transition states better.

I also use ni.getType() == ConnectivityManager.TYPE_WIFI instead of ni.getTypeName().equalsIgnoreCase("WIFI") because it is much more efficient to compare two int values than it is to compare two strings.

The following code works for me:

boolean HaveConnectedWifi = false;
boolean HaveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if ( ni != null )
{
    if (ni.getType() == ConnectivityManager.TYPE_WIFI)
        if (ni.isConnectedOrConnecting())
            HaveConnectedWifi = true;
    if (ni.getType() == ConnectivityManager.TYPE_MOBILE)
        if (ni.isConnectedOrConnecting())
            HaveConnectedMobile = true;
}
like image 64
Mark Allison Avatar answered Jan 01 '23 23:01

Mark Allison