Android检查是否有WiFi但没有互联网

时间:2015-01-16 16:10:27

标签: android connection wifi

我正在编写一个程序,我需要检查三种状态:1。如果我没有WiFi,2。如果我有WiFi但没有互联网连接(如果我打开路由器但拔掉以太网线), 3.如果我有WiFi和互联网连接。然后我会在我的应用程序中更改图标的颜色以表示其中一种状态(红色,黄色或绿色)。目前条件2不起作用,任何时候我拔掉我的路由器上的电缆进行测试,图标颜色从绿色变为红色。

public static void doPing(Context context) {

        String googleUrl = "https://www.google.com";
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        try {
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION);

            HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET);

            HttpClient client = new DefaultHttpClient(httpParameters);
            if (L) Log.i(TAG, "Calling: " + url );
            HttpGet getGoogle = getHttpGet(googleUrl);
            HttpResponse responseGoogle = client.execute(getGoogle);

            if (responseGoogle != null){
                 connectionIconView.setIcon(R.drawable.green_wifi);
            }
            else if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null){
                connectionIconView.setIcon(R.drawable.yellow_wifi);
            }
            else {
                 connectionIconView.setIcon(R.drawable.red_wifi);
            }

        } catch(Exception e) {
            if (L) Log.e(TAG, "Error during HTTP call");
            e.printStackTrace();
        }

1 个答案:

答案 0 :(得分:16)

检查无线网络是否可用

功能1

private boolean isWifiAvailable() {
    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    return wifi.isConnected();
}

在此之后,如果互联网可用,请像这样检查

功能2

 public static boolean isInternetAccessible(Context context) {
 if (isWifiAvailable()) {
    try {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500); 
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Couldn't check internet connection", e);
    }
} else {
    Log.d(LOG_TAG, "Internet not available!");
}
return false;
}

<强>条件

  1. 如果function 1返回false - >将颜色更改为RED
  2. 如果function 1返回true而function 2返回false - &gt;将颜色更改为黄色
  3. 如果两个函数都返回true - &gt;将颜色更改为绿色