简体   繁体   English

在Android应用程序中检测Internet连接?

[英]Detect Internet Connection in Android Application?

I have following method, which will check for the Internet connection in the device : 我有以下方法,它将检查设备中的Internet连接:

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. 例如设备已连接到路由器且路由器已打开但没有互联网可用,则此方法返回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? 是否可以在任何给定时间连接到Internet上的任何可能的主机? 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,NASA,您所在国家/地区的顶级提供商主页),如果可以,则您可能具有“实际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 尝试发送短信之前,请先检查Android中的网络覆盖范围

How to check internet access (INCLUDING tethering!) on Android? 如何在Android上检查互联网访问(包括网络共享!)?

How to determine the network unavailability in android 如何确定Android中的网络不可用性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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