Wifi已连接但无法正常工作

时间:2016-12-27 12:37:49

标签: android android-wifi

我正在创建一个依赖互联网的Android应用程序。如何处理手机连接到Wifi但实际上没有工作的情况? 与StatusBar中的wifi图标旁边有感叹号的情况一样?

2 个答案:

答案 0 :(得分:0)

添加权限:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

试试这个方法:

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(3000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return new Boolean(true);
            }
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return false;
}

答案 1 :(得分:0)

您可以检测到wifi速度,如果速度非常低,那么您可以处理这种情况。

首先,检查您的连接类型是否为wifi -

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

 NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
 boolean isConnected = activeNetwork != null &&
 activeNetwork.isConnectedOrConnecting();
 boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

 if(isWifi){
     WifiInfo wifiInfo = wifiManger.getConnectionInfo();
     int mbps = wifiInfo.getLinkSpeed();
 }