Android的:如何检查是否谷歌可用? [英] Android: How to check if Google is available?

查看:158
本文介绍了Android的:如何检查是否谷歌可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以提供更好,更快的方法来检查,如果谷歌可在Android的? 我观察到,connectiontimeout多年平均值给出TIME_OUT停止。而这不到一分钟要花更多...

 公共静态布尔isConnected(上下文的背景下){
            的NetworkInfo信息= Connectivity.getNetworkInfo(上下文);
            返程(资讯= NULL和放大器;!&安培; info.isConnected());
        }
        公共布尔checkInternetConnectivity(){

                尝试 {
                    HttpURLConnection的urlc =(HttpURLConnection类)(新的URL(
                            http://www.google.com).openConnection());
                    urlc.setRequestProperty(用户代理,测试);
                    urlc.setRequestProperty(连接,关闭);
                    urlc.setConnectTimeout(2000);
                    urlc.setReadTimeout(3000);
                    urlc.connect();
                    isInterNetAvailable = TRUE;
                    返程(urlc.getResponse code()== 200);
                }赶上(IOException异常E){
                    isInterNetAvailable = FALSE;
                    返回(假);
                }
            }
公共字符串getNWConnectivityText(){


        如果(Connectivity.isConnected(getSherlockActivity())==真){

            如果(checkInternetConnectivity()==真){
//如果(真== Connectivity.isConnectingToInternet(getSherlockActivity())){
//如果(真== Connectivity.isDataAvailable(getSherlockActivity())){

                返回谷歌是用;
            } 其他 {
                返回谷歌不可用;
            }

        } 其他 {
            返回无连接+\ t的;
        }
    }
 

解决方案

此外,以@星界投影的解决方案,你可能只是声明了一个插槽。我用我很多的项目下列code和超时肯定能行。

  Socket套接字;
最终的字符串主机=www.google.com;
最终诠释端口= 80;
最终诠释超时= 30000; //30秒

尝试 {
  插座=新的Socket();
  socket.connect(新InetSocketAddress(主机,端口),超时);
}
赶上(UnknownHostException异常UHE){
  Log.e(GoogleSock,我无法解决您所提供的主机!);
}
赶上(SocketTimeoutException如果STE){
  Log.e(GoogleSock,合理的时间量后,我无法连接,谷歌很可能是下来了!);
}
赶上(IOException异常IOE){
  Log.e(GoogleSock,嗯......突然断线,可能是你应该重新开始!);
}
 

这可能会非常棘手,但。 pcisely $ P $关于的UnknownHostException S,则可能需要更长的时间超时,约45秒 - 但在另一边,当你这通常发生无法解析主机,这样就morelike意味着你的网络连接已经missconfigured DNS解析(这是很可能不会)。

无论如何,如果你想要对冲你的赌注,你可以通过两种方式解决这个问题:

  • 不要使用一台主机,使用IP地址来代替。你可能会得到一些谷歌的IP地址只使用几次在主机上。例如:

     关了@我杀友〜/服务$平www.google.com
    平www.google.com(173.194.40.179)56(84)字节的数据。
     

  • 另一种解决方法是在启动看门狗线程,并完成所需的时间后,连接尝试。显然,forcely整理就意味着没有成功,所以你的情况,谷歌将下降。

----编辑----

我添加了如何将看门狗在这种情况下实施的一个例子。请记住,这是一个解决方法的情况下,它甚至不需要发生,但它应该做的伎俩,如果你真的需要。我要离开原来的code,所以你可能会看到不同:

  Socket套接字;

//你会使用此标志请检查是否你还在试图连接
布尔is_connecting = FALSE;

最终的字符串主机=www.google.com;
最终诠释端口= 80;
最终诠释超时= 30000; //30秒

//此方法将测试是否is_connecting标志仍被设置为true
私人无效stillConnecting(){
  如果(is_connecting){
    Log.e(GoogleSock,插座的时间太长建立连接,谷歌很可能是下来了!);
  }
}

尝试 {
  插座=新的Socket();
  is_connecting = TRUE;
  socket.connect(新InetSocketAddress(主机,端口),超时);

  //开始与postDelayed 30秒(当前的超时值)的处理程序,它会检查is_connecting是否仍然是正确的
  //这将意味着它很可能不会解析主机都连接失败
  // postDelayed是非阻塞的,所以不要担心你的线程被阻塞
  新的处理程序()。postDelayed(
    新的Runnable(){
      公共无效的run(){
        stillConnecting();
      }
    }, 时间到);
}
赶上(UnknownHostException异常UHE){
  is_connecting = FALSE;
  Log.e(GoogleSock,我无法解决您所提供的主机!);
  返回;
}
赶上(SocketTimeoutException如果STE){
  is_connecting = FALSE;
  Log.e(GoogleSock,合理的时间量后,我无法连接,谷歌很可能是下来了!);
  返回;
}
赶上(IOException异常IOE){
  is_connecting = FALSE;
  Log.e(GoogleSock,嗯......突然断线,可能是你应该重新开始!);
  返回;
}

//如果你已经达到了这一点,那岂不是插座去好了,谷歌达
is_connecting = FALSE;
 

注意:我假设你这样做,你应该(我的意思是,不是在主UI),而这将在一个线程中(可以使用的AsyncTask,线程,服务中的一个主题...)。

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" + "\t";
        }
    }

解决方案

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

This might be tricky, though. Precisely on UnknownHostExceptions, 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:

  • 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.
    

  • 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.

---- EDIT ----

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;

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的:如何检查是否谷歌可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆