2

デバイスがインターネットに実際に接続されているかどうか、ログインが必要な開かれたwifiホットスポットに接続されているかどうかを確認したい.
古典的なコード:

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected() && netInfo.isAvailable(){
   //connection on
}

デバイスが接続されていることを確認するには問題なく動作しますが、実際にはインターネットではありません。

私が使う :

URL url = new URL("http://www.google.com");
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setConnectTimeout((int)(1000 * TIMEOUT)); 
                urlConnection.connect();
                if (urlConnection.getResponseCode() == 200 && url.getHost().equals(urlConnection.getURL().getHost())) {
       //I am supposed to be connected
    }

ホットスポットに接続すると、通常はログイン ページにリダイレクトされるためです。ただし、ここでのテストでは、httpUrlConnection はリダイレクトされず、urlConnection.getURL.getHost() は実際には「google.com」です。

何をすべきか?

4

1 に答える 1

5

Android 4.0.1 android.net.wifi.WifiWatchdogStateMachine から取得:

private boolean isConnected() {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("http://clients3.google.com/generate_204");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setInstanceFollowRedirects(false);
            urlConnection.setConnectTimeout(10000);
            urlConnection.setReadTimeout(10000);
            urlConnection.setUseCaches(false);
            urlConnection.getInputStream();
            return urlConnection.getResponseCode() == 204;
        } catch (IOException e) {
            log("Walled garden check - probably not a portal: exception " + e);
            return false;
        } finally {
            if (urlConnection != null) urlConnection.disconnect();
        }
}
于 2012-07-31T13:59:23.153 に答える