Android - 检查互联网连接(使用需要登录的开放Wifi点)

时间:2012-02-01 10:12:18

标签: java android networking

我跟着这个 http://www.helloandroid.com/tutorials/it-internet-connection-checker-snippet检查我的Android设备上是否有互联网连接。

代码块看起来像这样

URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(1000 * 5); // Timeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
    // http response is OK
    Log.d("db", "Connection to " + url.toString() + " successful!");
    return true;
}

但是,我的设备已连接到开放的Wifi点,这需要在访问互联网之前登录网页。即使没有登录,此代码似乎也会返回true。

想知道我能做什么?

3 个答案:

答案 0 :(得分:1)

如果您拥有自己的域,请创建一个仅包含您选择的一个关键字的网页。 例如:“成功”

现在连接到该页面而不是谷歌并检查它是否返回“成功”。

URL url = new URL("http://www.yourdomain.com/yourpage.html");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(1000 * 5); // Timeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
    // http response is OK

    InputStream in = urlc.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    String line = reader.readLine();
    in.close();
    if (line == "success"){
        Log.d("db", "Connection to " + url.toString() + " successful!");
        return true;
    } else {
        return false;
    }
}

答案 1 :(得分:0)

我认为你必须使用这种方法 检查我可用的互联网连接。

public boolean isOnline()
        {

             ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
             NetworkInfo ni = cm.getActiveNetworkInfo();
             boolean result = false;
             if(ni != null )
             {
                 if(  ni.getState() == NetworkInfo.State.CONNECTED )
                 {
                     result = true;
                 }
             }

             return result;

            } 

答案 2 :(得分:0)

private boolean checkInternetConnection() {
    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getActiveNetworkInfo() != null
            && conMgr.getActiveNetworkInfo().isAvailable()
            && conMgr.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        Toast toast = Toast
                .makeText(
                        getApplicationContext(),
                        "No Internet Connection Found !!! Please Connect To Internet First",
                        Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.sleep(5000);
                    finish();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return false;
    }
}