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

标签 android

我正在开发一个Android应用程序,需要检查互联网连接。当设备的WI-FI关闭时,它工作得很好,但是当我打开Wi-Fi但不连接到可用网络时,它是强制关闭。可能是什么问题?请帮忙 bool 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;

}

最佳答案

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

想法:

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;
        }
    }

关于android - WI-FI已打开但未连接到网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12257295/

相关文章:

java - Android(Java)网络编程资源

android - 如何禁用文本输入中文本下的行 android react native

android - 应用程序 (26.1.0) 和测试应用程序 (27.1.1) 的已解决版本不同

android - 选项卡文本随 viewpager 消失

android - 使用 9 个补丁或各种大小的图标

java - onactivityresult() 永远不会被调用

javascript - kendo.navigate 和更改 location.hash 之间的区别

java - 在 Android 应用程序中将两部手机/用户链接在一起

android - 在 Visual Studio Emulator for Android 中使用代理

android - 使用 setRetainInstance(true) 将 Context 传递给 Fragment 内的 ArrayAdapter 会导致泄漏?