简体   繁体   中英

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 ?

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'.

我为您看到的唯一方法是尝试连接到google这样的网站,如果您获得结果,则可以确定,否则就没有互联网活动。

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;

    }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM