aman.nepid
aman.nepid

Reputation: 3054

Detect Internet Connection in Android Application?

I have following method, which will check for the Internet connection in the device :

public static boolean checkInternetConnection(Context context) {
    ConnectivityManager connectivityManager = 
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager.getActiveNetworkInfo() != null
            && connectivityManager.getActiveNetworkInfo().isAvailable()
            && connectivityManager.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        return false;
    }

}

But after a while I found out that this method only checks for the Network Connectivity; like the device is connected to a router and the router is ON but no internet is available, this method returns true.

So How to know that there is actual internet or not ?

Upvotes: 1

Views: 361

Answers (4)

Rod Burns
Rod Burns

Reputation: 2244

There are lots of questions already on this topic with answers with suggested solution. Try taking a look at some of these.

Check Network Coverage in Android before trying to send SMS

How to check internet access (INCLUDING tethering!) on Android?

How to determine the network unavailability in android

Upvotes: 0

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52936

So what is 'actual internet'? The ability to connect to any possible host on the Internet at any given time? A bit hard to test, no? Try connecting to a well-known server (Google, NASA, your country's top provider home page), and if it works, you probably have 'actual Internet'.

Upvotes: 4

Nima Sa
Nima Sa

Reputation: 89

The only way I see for you is trying to connect to a website like google and if you get result then you can be sure of it, else no internet activity.

Upvotes: 1

Mehul Ranpara
Mehul Ranpara

Reputation: 4255

try this function...

public static Boolean checknetwork(Context mContext) 
    {

        NetworkInfo info = ((ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE))
                .getActiveNetworkInfo();
        if (info == null || !info.isConnected()) 
        {

            return false;
        }
        if (info.isRoaming()) 
        {
            // here is the roaming option you can change it if you want to
            // disable internet while roaming, just return false
            return true;
        }

        return true;

    }

Upvotes: 0

Related Questions