简体   繁体   English

Android-如何检查设备是否可以连接互联网?

[英]Android - How to check, device has Internet connection?

This code works: 此代码有效:

public static boolean isConnected()
{
    ConnectivityManager cm = (ConnectivityManager)App.getAppContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni != null) {
        if (ni.getType() == ConnectivityManager.TYPE_WIFI)
            if (ni.isConnected())
                return true;
        if (ni.getType() == ConnectivityManager.TYPE_MOBILE)
            if (ni.isConnected())
                return true;
        if (ni.getType() == ConnectivityManager.TYPE_ETHERNET)
            if (ni.isConnected())
                return true;
    }
    return false; //none of connections available
}

The question is: do we also have to check TYPE_MOBILE_DUN , TYPE_WIMAX and TYPE_VPN ? 问题是:我们还需要检查TYPE_MOBILE_DUNTYPE_WIMAXTYPE_VPN吗?

Can a device be connected to the Internet over Bluetooth? 设备可以通过蓝牙连接到Internet吗?

Just one comment. 只是一条评论。 Think what do you need and remember to be connected to a wifi router doesn't mean you have internet connection or that you are able to reach any point of interest like a backend server. 想一想您需要什么,并记住连接到wifi路由器并不意味着您可以连接互联网,也可以像后端服务器那样到达任何兴趣点。 If your app needs to access a service to work, may be the best way it is to check if you can reach it in an early stage through an async call and only proceed if you could validate that connection. 如果您的应用需要访问服务才能正常工作,那么最好的方法就是检查您是否可以通过异步调用尽早到达该服务,并且只有在您可以验证该连接的情况下才能继续操作。

Try to make a simple GET request to http://www.google.com . 尝试向http://www.google.com发出一个简单的GET请求。 If your response code is 200 or 400 Then the internet connection exists. 如果您的响应代码为200或400,则说明存在互联网连接。

protected static boolean hasInternetAccess()
{
    try
    {
        URL url = new URL("http://www.google.com");

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application:1");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000 * 30);
        urlc.connect();

        // http://www.w3.org/Protocols/HTTP/HTRESP.html
        if (urlc.getResponseCode() == 200 || urlc.getResponseCode() > 400)
        {
            // Requested site is available
            return true;
        }
    }
    catch (Exception ex)
    {
        // Error while trying to connect
        return false;
    }
    return false;
}

For more info, refer to: The perfect function to check Android internet connectivity including bluetooth pan 有关更多信息,请参阅: 完善的功能,可检查包括蓝牙声像在内的Android Internet连接

This is all I use: 这就是我所使用的:

public static boolean isOffline() {
    ConnectivityManager cm = (ConnectivityManager) BigOvenApplication.getInstance()
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    return netInfo == null || !netInfo.isConnected();
}

I don't think you need anything more than that. 我认为您只需要这些。

Just call the method isConnectedToNetwork to check whether it has connection or not. 只需调用方法isConnectedToNetwork来检查它是否具有连接。 Write this method in a common class file. 在公共类文件中编写此方法。 Thereby you can use simple methodcall where ever you need. 因此,您可以在任何需要的地方使用简单的方法调用。

public static boolean isConnectedToNetwork(Context thisActivity) {
        ConnectivityManager connMgr = (ConnectivityManager) thisActivity.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
        if (activeInfo != null && activeInfo.isConnected()) {
            return true;
        }
        return false;
    }

Check before you start the operation. 在开始操作之前进行检查。 //thisActivity means getActivity() for fragments // thisActivity表示片段的getActivity()

   if (isConnectedToNetwork(thisActivity)) {
           // your operation code follows
     } else {
          //show alert box that there is no internet connection
     }

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

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