Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect If there is no internet connection

Tags:

android

wifi

I have a code to determine if there is a network connection or not :

    ConnectivityManager cm = (ConnectivityManager)  getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnected()) 
    {
        // There is an internet connection
    }

But if there is a network connection and no internet this is useless. I have to ping a website and wait for a response or timeout to determine the internet connection:

    URL sourceUrl;
    try {
        sourceUrl = new URL("http://www.google.com");
        URLConnection Connection = sourceUrl.openConnection();
        Connection.setConnectTimeout(500);
        Connection.connect();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

        // no Internet
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

        // no Internet
    }

But it is a slow detection. I should learn a good and fast way to detect it.

Thanks in advance.

like image 476
Tuna Karakasoglu Avatar asked Oct 07 '22 02:10

Tuna Karakasoglu


2 Answers

Try following method to detect different type of connection:

private boolean haveNetworkConnection(Context context)
{
    boolean haveConnectedWifi = false;
    boolean haveConnectedMobile = false;

    ConnectivityManager cm = (ConnectivityManager) Your_Activity_Name.this.getSystemService(Context.CONNECTIVITY_SERVICE);
    // or if function is out side of your Activity then you need context of your Activity
    // and code will be as following
    // (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo[] netInfo = cm.getAllNetworkInfo();
    for (NetworkInfo ni : netInfo)
    {
        if (ni.getTypeName().equalsIgnoreCase("WIFI"))
        {
            if (ni.isConnected())
            {
                haveConnectedWifi = true;
                System.out.println("WIFI CONNECTION AVAILABLE");
            } else
            {
                System.out.println("WIFI CONNECTION NOT AVAILABLE");
            }
        }
        if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        {
            if (ni.isConnected())
            {
                haveConnectedMobile = true;
                System.out.println("MOBILE INTERNET CONNECTION AVAILABLE");
            } else
            {
                System.out.println("MOBILE INTERNET CONNECTION NOT AVAILABLE");
            }
        }
    }
    return haveConnectedWifi || haveConnectedMobile;
}
like image 120
Chintan Raghwani Avatar answered Oct 20 '22 08:10

Chintan Raghwani


The problem with all such schemes is that 'the internet' does not exist as an entity. There is a reason why failed connection attempts are reported as 'unreachable' or 'cannot connect to server at blahblah'. Examples:

1) You have no signal. Are you connected to the internet? Will PING succeed? Can you connect to your target server?

2) You have a signal, but your provider data allowance has been exceeded. Are you connected to the internet? Will PING succeed? Can you connect to your target server?

3) Your provider connection is fine, but their backbone router is down. Are you connected to the internet? Will PING succeed? Can you connect to your target server?

4) Your provider connection is fine, their backbone router is up but the fibre connection to country X where the server is has been interrupted by some drunken Captain and his ship's anchor. Are you connected to the internet? Will PING succeed? Can you connect to your target server?

5) All the links to the target country are up but Fred, with his ditch-digging JCB, has cut the power cable to the server farm. One of Fred's other jobs is to service the backup generator:( Are you connected to the internet? Will PING succeed? Can you connect to your target server?

6) All the hardware is up, but the server code was written by Fred before he was demoted to ditch-digger for incompetence and has now crashed, again. Are you connected to the internet? Will PING succeed? Can you connect to your target server?

7) Fred has had a day off, but his replacement, competent server admin has blocked off ICMP ping in the routers to prevent ping DOS attacks. Are you connected to the internet? Will PING succeed? Can you connect to your target server?

So, the ony way to be sure is to attempt to connect to the target server and see what happens.

You can surely detect some negative cases more quickly - surely if there is no signal, you cannot get a connection:) Past that, you should just try to connect. Tell the user what is going on, use a timeout and supply the user with a 'Cancel' button. That's about the best you can do.

like image 26
Martin James Avatar answered Oct 20 '22 08:10

Martin James