Android:如何检查Google是否可用?

有人可以提供更好,更快的方法来检查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";
        }
    }

解决方法:

除了@ 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!");
} 

但是,这可能很棘手.恰好在UnknownHostExceptions上,超时可能需要更长的时间,大约为45秒-但另一方面,这通常发生在您无法解析主机时,因此更可能意味着您的Internet访问配置了错误的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线程并在所需时间后完成连接尝试.显然,强行完成并不意味着成功,因此就您而言,Google将会倒台.

—-编辑—-

我要添加一个示例,说明在这种情况下如何实现看门狗.请记住,这是解决甚至不需要发生的情况的解决方法,但是如果您确实需要,它应该可以解决问题.我将保留原始代码,因此您可能会看到不同之处:

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,线程,线程…) .

上一篇:iOS学习之Object-C语言内存管理


下一篇:【Java转Android】39.HttpURLConnection的使用