WI-FI已开启但未连接到网络

时间:2012-09-04 05:28:55

标签: android

我正在开发一个需要检查互联网连接的Android应用程序。当设备的WI-FI关闭时它工作得很好但是当我打开Wi-Fi但没有连接到可用的网络时,它是强行关闭。可能是什么问题?请帮助 boolean isNetworkConnectionAvailable(){

  boolean connected = false;

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

    if (cm != null) {
        NetworkInfo ni = cm.getActiveNetworkInfo();

        if(ni != null){

                if(ni.isConnected())
                connected = true;
                else
                    connected=false;

           }

    }



    return connected;

}

1 个答案:

答案 0 :(得分:5)

当您的设备连接到WIFI但WIFI未连接到Internet时,您的问题是返回true。您可以通过以编程方式执行ping命令来解决此问题。

IDEA:

1)检查您是否连接到WIFI。

2)如果您连接到wifi ping以检查网络可用性。

<强>代码:

public static boolean isOnline(Context con,String url){

    ConnectivityManager cm = (ConnectivityManager)con.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) { 
        if(u!=null){
            return ping(url);
        }else{
            return true;
        }
    }else{
        return false;
    }
}

Ping方法:

public static boolean ping(String u) { 
        try {
            URL url = new URL(u);
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(500); // Time is in Milliseconds to wait for ping response
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                Log.i(TAG, "* ping  with ResponseCode: "+urlc.getResponseCode());
                return true;
            }else{
                Log.i(TAG, "* Connection is too slow with ResponseCode: "+urlc.getResponseCode());
                return false;
            }
        }catch (MalformedURLException e1){
            Log.e(TAG,"Erroe in URL to ping"+e1);
            return false;
        }catch (IOException e){
            Log.e(TAG,"Error in ping"+e);
            return false;
        }
    }