我有一个代码,以确定是否有网络连接或没有:检测如果没有互联网连接
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
}
但它是一个缓慢的检测。我应该学习一种快速,方便的方法来检测它。
在此先感谢。
这意味着你也使用WIFI。我对吗??? – 2012-07-30 09:15:37
是的,我只使用Wifi。 – 2012-07-30 09:17:52
那么问题是什么? – 2012-07-30 09:19:28