Android: How to check if Google is available?(Android:如何检查 Google 是否可用?)
问题描述
谁能提供更好更快的方法来检查 Google 是否在 Android 中可用?我观察到连接超时不会在给定的超时时间内停止.而是需要一分钟以上..
Can someone provide better and faster way to check if Google is available in Android? I have observed that connectiontimeout doesnot stop in given time_out. rather it takes more than a minute..
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" + " ";
}
}
推荐答案
除了@astral-projection 的解决方案,您可以简单地声明一个Socket
.我在我的许多项目中都使用了以下代码,并且超时确实有效.
Additionally to @astral-projection's solution, you may simply declare a Socket
. I use the following code on many of my projects and the timeout definitely works.
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
上,超时可能需要更长的时间,大约 45 秒 - 但另一方面,这通常发生在 您 无法解析主机时,因此更喜欢表示您的互联网访问配置错误的 DNS 解析(这不太可能).
This might be tricky, though. Precisely on UnknownHostException
s, it may take longer to timeout, about 45 seconds - but on the other side, this usually happens when you cannot resolve the host, so that would morelike mean that your internet access has missconfigured DNS resolution (which is not probable).
无论如何,如果你想对冲你的赌注,你可以通过两种方式解决这个问题:
Anyway, if you want to hedge your bets, you could solve this by two ways:
不要使用主机,而是使用 IP 地址.只需在主机上多次使用
ping
即可获得多个 Google 的 IP.例如:
Don't use a host, use an IP address instead. You may get several Google's IPs just using
ping
several times on the host. For instance:
shut-up@i-kill-you ~/services $ ping www.google.com
PING www.google.com (173.194.40.179) 56(84) bytes of data.
另一种解决方法是启动 WatchDog
线程并在所需时间后完成连接尝试.显然,强行结束意味着没有成功,所以在你的情况下,谷歌会倒闭.
Another workaround would be starting a WatchDog
thread and finish the connection attempt after the required time. Evidently, forcely finishing would mean no success, so in your case, Google would be down.
---- 编辑----
我正在添加一个示例,说明在这种情况下如何实现看门狗.请记住,这是一种甚至不需要发生的情况的解决方法,但是如果您确实需要,它应该可以解决问题.我将保留原始代码,因此您可能会看到差异:
I'm adding an example of how would a watchdog be implemented in this case. Keep in mind it's a workaround to a situation that doesn't even need to happen, but it should do the trick if you really need to. I'm leaving the original code so you may see the differences:
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;
注意:我假设你在你应该做的地方(我的意思是,不是在主 UI 中)并且这是在一个线程中进行的(你可以使用 AsyncTask,一个线程,服务中的线程...).
Note: I'm assuming you're doing this where you should (I mean, not in the main UI) and that this is going within a Thread (you can use AsyncTask, a Thread, a Thread within a Service...).
这篇关于Android:如何检查 Google 是否可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android:如何检查 Google 是否可用?
基础教程推荐
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01