我正在开发一个android应用程序,我想知道检查Internet连接是否存在的最佳方法.我曾尝试使用连接管理器和networkinfo类,但无济于事,因为我的应用程序在没有网络的情况下不断崩溃,否则我会使用HttpConnection方法.有人可以提出宝贵的建议吗?
解决方法:
URL myurl = new URL(url);
URLConnection connection = myurl.openConnection();
connection.setConnectTimeout(20 * 1000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = -1;
try {
responseCode = httpConnection.getResponseCode();
} catch (Exception e1) {
throw e1;
}
if (responseCode == HttpURLConnection.HTTP_OK) {
//connection is OK and do what you want
//...
}
else
{
//connection is not OK
httpConnection.disconnect();
}