有人可以提供更好,更快的方式来检查Google是否在Android中可用吗? 我观察到connectiontimeout在给定的time_out中没有停止。相反,它需要一分多钟..
public static boolean isConnected(Context context){
NetworkInfo info = Connectivity.getNetworkInfo(context);
return (info != null && info.isConnected());
}
public boolean checkInternetConnectivity() {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL(
"http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000);
urlc.setReadTimeout(3000);
urlc.connect();
isInterNetAvailable = true;
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
isInterNetAvailable = false;
return (false);
}
}
public String getNWConnectivityText() {
if (Connectivity.isConnected(getSherlockActivity()) == true) {
if (checkInternetConnectivity() == true) {
// if (true == Connectivity.isConnectingToInternet(getSherlockActivity())) {
// if (true == Connectivity.isDataAvailable(getSherlockActivity())) {
return "google is available";
} else {
return "google is not available";
}
} else {
return "no connectivity" + "\t";
}
}
答案 0 :(得分:4)
除@ astral-projection的解决方案外,您可以简单地声明Socket
。我在我的许多项目中使用以下代码,超时肯定有效。
Socket socket;
final String host = "www.google.com";
final int port = 80;
final int timeout = 30000; // 30 seconds
try {
socket = new Socket();
socket.connect(new InetSocketAddress(host, port), timeout);
}
catch (UnknownHostException uhe) {
Log.e("GoogleSock", "I couldn't resolve the host you've provided!");
}
catch (SocketTimeoutException ste) {
Log.e("GoogleSock", "After a reasonable amount of time, I'm not able to connect, Google is probably down!");
}
catch (IOException ioe) {
Log.e("GoogleSock", "Hmmm... Sudden disconnection, probably you should start again!");
}
但是,这可能很棘手。正好在UnknownHostException
s,可能需要更长时间才能超时,大约45秒 - 但另一方面,这通常发生在你无法解析主机时,这更像是意味着你的互联网访问错误配置了DNS解析(这是不可能的)。
无论如何,如果你想对冲你的赌注,你可以通过两种方式来解决这个问题:
请勿使用主机,而是使用IP地址。您可以在主机上多次使用ping
获取多个Google的IP。例如:
shut-up@i-kill-you ~/services $ ping www.google.com
PING www.google.com (173.194.40.179) 56(84) bytes of data.
另一种解决方法是启动WatchDog
线程并在所需时间后完成连接尝试。显然,强制整理意味着没有成功,所以在你的情况下,谷歌会失败。
----编辑----
我正在添加一个示例,说明在这种情况下如何实现看门狗。请记住,这是一种甚至不需要发生的情况的解决方法,但如果您确实需要,它应该可以解决问题。我将离开原始代码,以便您可以看到差异:
Socket socket;
// You'll use this flag to check wether you're still trying to connect
boolean is_connecting = false;
final String host = "www.google.com";
final int port = 80;
final int timeout = 30000; // 30 seconds
// This method will test whether the is_connecting flag is still set to true
private void stillConnecting() {
if (is_connecting) {
Log.e("GoogleSock", "The socket is taking too long to establish a connection, Google is probably down!");
}
}
try {
socket = new Socket();
is_connecting = true;
socket.connect(new InetSocketAddress(host, port), timeout);
// Start a handler with postDelayed for 30 seconds (current timeout value), it will check whether is_connecting is still true
// That would mean that it won't probably resolve the host at all and the connection failed
// postDelayed is non-blocking, so don't worry about your thread being blocked
new Handler().postDelayed(
new Runnable() {
public void run() {
stillConnecting();
}
}, timeout);
}
catch (UnknownHostException uhe) {
is_connecting = false;
Log.e("GoogleSock", "I couldn't resolve the host you've provided!");
return;
}
catch (SocketTimeoutException ste) {
is_connecting = false;
Log.e("GoogleSock", "After a reasonable amount of time, I'm not able to connect, Google is probably down!");
return;
}
catch (IOException ioe) {
is_connecting = false;
Log.e("GoogleSock", "Hmmm... Sudden disconnection, probably you should start again!");
return;
}
// If you've reached this point, it would mean that the socket went ok, so Google is up
is_connecting = false;
注意:我假设你正在这样做(我的意思是,不在主用户界面中)并且这是在一个线程内(你可以使用AsyncTask,一个线程) ,服务中的线程......)。
答案 1 :(得分:1)
广播接收器可能会派上用场:
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getActivity(), "Connection reset, rolling back", Toast.LENGTH_LONG).show();
}
};
它也是电池友好的。
也不要忘记取消注册:( onDestroy())
getActivity().unregisterReceiver(networkStateReceiver);
答案 2 :(得分:1)
正如Astral所说,你可以使用BroadcastReceiver来获取互联网连接的状态,这是检查互联网连接的最佳方式;但是如果您尝试连接的服务器已关闭或没有响应,那么只是为了安全起见创建一个超时循环。 如果在特定时间内没有从服务器回复,则取消请求并向用户显示错误消息。