首页 文章

Android:检查网络和真实的互联网连接

提问于
浏览
2

下面是一段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" />

但是,拥有有效的网络接口并不能保证特定的网络服务可用 .

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

常见场景:

  • Android设备连接到Wi-Fi,后来证明是专用网络 . 因此isNetworkAvailable将返回该网络已连接,但无法连接到任何其他服务

  • 有时电话信号显示它已连接到服务提供商数据计划 . 所以网络连接是真的,但仍然无法访问谷歌/雅虎 .

One way is to check if "isNetworkAvailable" function returns TRUE, then run following 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();
  }

但我认为这不是一个好方法,因为它可能会耗费大量时间

So is there any alternative efficient (in terms of time taken,speed) way ensure that we are connected to network as well as reachable to most common internet services ?

3 回答

  • 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

    Issue #1:
    Android设备连接到Wi-Fi,后来证明是专用网络 .
    因此 isNetworkAvailable 将返回该网络已连接,但无法连接到任何其他服务 .

    Issue #2:
    有时电话信号显示它已连接到服务提供商数据计划 . 所以网络连接是真的,但仍然无法访问谷歌/雅虎 .

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

    最终,您需要 Monitor 网络连接的变化,

    Step 1:

    只需注册 BroadcastReceiver 即可执行以下操作

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

    Step 2:

    当您在 onReceive(Context context,Intent intent) 方法上获得回调时,请检查连接状态 .

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

    //除了 EXTRA_NO_CONNECTIVITY 之外,还有其他参数也可用于监控

    Reference:

    Examples:

    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 Docs:

    Connectivity Monitoring

    Connectivity Manager

    我希望它会有所帮助!!

  • 2

    使用此代码检查互联网连接,它检查设备上的所有互联网连接 . 并且确保你已经在menifest中添加了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");
            }
    

相关问题