0

我正在使用下面的代码检查是否有可用的网络,但有时网络可用但没有数据传输,这使我的互联网连接失败并引发异常。

这是代码:

    public boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
} 

那么,谁能帮我找到解决方案?

谢谢

4

2 回答 2

1

我正在使用以下代码检查连接,因为我认为仅获取网络信息并不能保证互联网连接。因此,我认为最好向远程 URL 发出实际的 HTTP 请求并查看它是否成功。

    public static boolean isInternetAvailable(Context cxt) {

        ConnectivityManager cm = (ConnectivityManager) cxt
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo netInfo = cm.getActiveNetworkInfo();

        if (netInfo != null && netInfo.isConnectedOrConnecting() && canHit()) {

            Log.i(App.TAG, "Network connection available.");
            return true;
        }

        return false;
    }

    public static boolean canHit() {

        try {

            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();
            urlConnection.setConnectTimeout(3000);
            urlConnection.connect();
            urlConnection.disconnect();
            return true;

        } catch (Exception e){  
            e.printStackTrace();
            return false;
        } 
    }
于 2013-08-14T16:46:59.043 回答
0

The user may be on a BT openzone or similar connection where they have a connection but do not have internet access until they supply a password via a web browser. Data connection issues are always going to happen, you just have to handle them in each case.

Also checkout

isConnectedOrConnecting()

Which checks whether the user is still establishing a connection. See http://developer.android.com/reference/android/net/NetworkInfo.html

于 2013-08-14T16:50:18.637 回答