我有一段代码用于确定是否存在网络连接:
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
// There is an internet connection
}
但是,如果有网络连接而没有互联网连接,这就没有用了。我必须ping一个网站并等待响应或超时来确定互联网连接:
URL sourceUrl;
try {
sourceUrl = new URL("http://www.google.com");
URLConnection Connection = sourceUrl.openConnection();
Connection.setConnectTimeout(500);
Connection.connect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// no Internet
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// no Internet
}
但是这是一种缓慢的检测方法。我需要学习一种好的、快速的检测方法。
提前致谢。