【问题标题】:how to check that internet on local wifi is available or not?如何检查本地wifi上的互联网是否可用?
【发布时间】:2011-12-16 13:49:02
【问题描述】:

我需要在我的应用程序中检查本地 wifi 上的互联网是否可用,我试过了

requestRouteToHost 但它总是返回 false ,所以请帮忙

【问题讨论】:

  • 你只是想测试一下手机是否有连接?
  • 我需要连接到启用了 wifi 的设备,但我需要检查该 wifi 用户是否可以打开任何网站或可以访问互联网

标签: android android-wifi


【解决方案1】:

这是测试设备是否有 INTERNET 连接周期的最佳方法。

public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
    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, "Error checking internet connection", e);
    }
} else {
    Log.d(LOG_TAG, "No network available!");
}
return false;

}

这是一种检查它是否有 wifi 连接或数据连接的方法。

  private boolean checkInternetConnection()
  {

    ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);

    // ARE WE CONNECTED TO THE NET

    if (conMgr.getActiveNetworkInfo() != null

            && conMgr.getActiveNetworkInfo().isAvailable()

            && conMgr.getActiveNetworkInfo().isConnected()) 
    {

    return true;

    }
    else 
    {
    return false;

    }
}

【讨论】:

    猜你喜欢
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2012-02-19
    相关资源
    最近更新 更多