无线网络连接上,但没有连接到网络 [英] WI-FI is on but not connected to network

查看:128
本文介绍了无线网络连接上,但没有连接到网络的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个Android应用程序,需要检查网络connection.When了Wi-Fi的设备已关闭其工作完全正常,但是当我打开无线网络连接,但不连接到可用的网络,它是力closing.What可能是问题?请帮助 布尔isNetworkConnectionAvailable(){

I am developing an android app which requires to check internet connection.When the WI-FI of the device is off it works perfectly fine but when I turn on the Wi-Fi but do not connect to the available network,it is force closing.What could be the problem?Please Help 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;

}

推荐答案

您的问题是,你还真当你的色器件连接到WIFI,但WIFI无法连接到internet.You可以通过编程执行ping命令解决这个问题。

Your problem is you return true when your devise is connected to the WIFI but WIFI does not connect to the internet.You can solve this by executing ping command programatically.

IDEA:

1)检查您的连接到WIFI。

1) Check your are connect to the WIFI.

2),如果你连接到WiFi网络ping命令检查网络可用性。

2)if you connect to the wifi ping to check network availability.

code:

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方法:

Ping method:

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

这篇关于无线网络连接上,但没有连接到网络的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆