2014-01-10 88 views
2

下面是一段可以正常工作以检查网络是否连接的Android代码。Android:检查网络和真实的互联网连接

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" /> 

但是具有活动的网络接口并不能保证特定的网络服务可用。

很多时间发生,我们连接到网络,但仍无法访问常见的互联网网络服务,例如,谷歌

常见的场景:连接到Wi-Fi,这原来是一个私人 网络

  1. Android设备。所以isNetworkAvailable将返回该网络已连接,但可能 不能连接到任何其他服务
  2. 有时电话信号显示它连接到服务提供商的数据计划。所以网络连接是真实的,但仍然无法访问谷歌/雅虎。

一种方法是检查是否“isNetworkAvailable”函数返回TRUE,则下面的代码

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(); 
    } 

运行,但我想这是不是因为它可能会消耗大量的时间

一个好办法

那么,有没有其他有效的方法(就时间和速度而言),确保我们连接到网络以及可以访问大多数常见的互联网服务?

+0

这是一种检查的好方法,但是您可以针对您的问题以有组织的方式写出给定的答案。 –

+1

我会建议你看看这个http://stackoverflow.com/questions/8919083/checking-host-reachability-availability-in-android – 2014-01-10 09:30:02

回答

1

检查这个代码...它为我工作:)

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(); 

} 

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

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的代码https://stackoverflow.com/a/5803489/2603719

我希望我可以帮你

+0

谢谢!但是比我的代码更有效率(根据所花时间)? – RDX

+1

您也可以设置定时器。 '@Override \t protected void onCreate(Bundle savedInstanceState){ \t \t super.onCreate(savedInstanceState); 处理程序H =新的处理程序(){ \t \t // \t \t // @Override 公共无效的handleMessage(消息MSG){ 如果(msg.what!= 1){// NO INTERNET}否则{//互联网 } } }; isNetworkAvailable(h,2000);}' – elHomer

+0

这似乎是更好的方法! – RDX

1

问题#1:
连接到Wi-Fi,这原来是一个私有网络的Android设备。
因此isNetworkAvailable将返回该网络已连接,但无法连接到任何其他服务。

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

I'm not sure about Issue #1 but I'm sure that following approach will solve Issue #2. 

最终,你将需要监视器在网络连接的改变,

第1步:

只为以下行动

<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>

注册 BroadcastReceiver

步骤2:

当您收到onReceive(Context context,Intent intent)回调方法时,请检查连接状态。

即: boolean isConnected = getIntent().getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);

//除了EXTRA_NO_CONNECTIVITY,还有其他参数也将是有用的监视

参考:

实例:

Working Example of Step1,Step2: how-to-monitor-network-connectivity-in-android

Android-getting-notified-of-connectivity-changes

Github: Example for network-detect-notify

Android的文档:

Connectivity Monitoring

Connectivity Manager

我希望这会有所帮助!

0

使用此代码来检查互联网连接,它检查设备上的所有互联网连接。并确保您已在清单中添加了Internet权限。

 boolean flag=false; 
     ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); 
     if (connectivity != null) 
     { 
      NetworkInfo[] info = connectivity.getAllNetworkInfo(); 
      if (info != null) 
       for (int i = 0; i < info.length; i++) 
        if (info[i].getState() == NetworkInfo.State.CONNECTED) 
        { 
         flag=true; 

        } 

     } 
     if(flag==true) 
     { 
      Log.e("TAG","Internet Is Connected"); 
     } 
     else 
     { 
       Log.e("TAG","Internet Is Not Connected"); 
     }