安卓:检查网络和实时互联网连接 [英] Android: Check network and real internet connectivity

查看:159
本文介绍了安卓:检查网络和实时互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一块的Andr​​oid code的工作正常,检查网络连接或没有。

Below is the piece of Android code which works fine to check if network is connected or not.

public static boolean isNetworkAvailable(Context context) 
{
    ConnectivityManager mConnectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    return (mConnectivityManager != null && mConnectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()) ? true : false;
}

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

但有一个活跃的网络接口不能保证一个特定的网络服务。

But having an active network interface doesn't guarantee that a particular networked service is available.

很多时候发生,我们都连接到网络,但还没有到达共同的互联网网络服务,例如,谷歌

A lot of time happens that we are connected to network but still not reachable to common internet network services, e.g. Google

常见的场景:


  1. 连接到Wi-Fi无线Android设备,这原来是一个私人
    网络。所以isNetworkAvailable将返回的网络连接,但也
    不连接到任何其他服务

  2. 有些时候,手机信号显示它连接到服务提供商的数据计划。所以网络连接是真的,但仍无法访问谷歌/雅虎。

的一种方法是检查是否isNetworkAvailable函数返回TRUE,然后按照code运行

HttpGet request = new HttpGet(url));
   HttpParams httpParameters = new BasicHttpParams();
   int timeoutConnection = 60000;
   HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
   int timeoutSocket = 60000;
   HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

   DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
   request.addHeader("Content-Type", "application/json");
   HttpResponse response = httpClient.execute(request);

   HttpEntity entity = response.getEntity();


     if (entity != null)
      {
         result = EntityUtils.toString(entity);
      }

   }
 catch (SocketException e)
  {
     return "Socket Exceptiopn:" + e.toString();
  }
 catch (Exception e)
  {
     return "General Execption:" + e.toString();
  }

但我认为这并不是因为它可能会消耗大量时间的好方法。

But I think this is not an good way because it may consume lot of time

那么,有没有替代的高效率(在时间上采取的,速度)的方式确保我们连接到网络,以及可达最常用的互联网服务?

推荐答案

检查该code ......它为我工作:)

check this code... it worked for me :)

public static void isNetworkAvailable(final Handler handler, final int timeout) {

        // ask fo message '0' (not connected) or '1' (connected) on 'handler'
        // the answer must be send before before within the 'timeout' (in milliseconds)

        new Thread() {

            private boolean responded = false;

            @Override
            public void run() {

                // set 'responded' to TRUE if is able to connect with google mobile (responds fast)

                new Thread() {

                    @Override
                    public void run() {
                        HttpGet requestForTest = new HttpGet("http://m.google.com");
                        try {
                            new DefaultHttpClient().execute(requestForTest); // can last...
                            responded = true;
                        } catch (Exception e) {}
                    }

                }.start();

                try {
                    int waited = 0;
                    while(!responded && (waited < timeout)) {
                        sleep(100);
                        if(!responded ) { 
                            waited += 100;
                        }
                    }
                } 
                catch(InterruptedException e) {} // do nothing 
                finally { 
                    if (!responded) { handler.sendEmptyMessage(0); } 
                    else { handler.sendEmptyMessage(1); }
                }

            }

        }.start();

}

然后,我定义的处理程序:

Then, I define the handler:

Handler h = new Handler() {

    @Override
    public void handleMessage(Message msg) {

        if (msg.what != 1) { // code if not connected

        } else { // code if connected

        }

    }
};

和启动测试:

isNetworkAvailable(h,2000); // get the answser within 2000 ms

从Gilbou http://stackoverflow.com/a/5803489/2603719

code

我希望我可以帮你。

I hope i can Help you

这篇关于安卓:检查网络和实时互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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