Android检查wifi连接

时间:2012-06-14 12:31:34

标签: android httpurlconnection

我在Android中有一个关于wifi连接的具体问题。我正在开发一个从Web服务器下载一些数据的项目,每次开始同步之前我都在检查这样的互联网连接:

    public static boolean isOnline(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

public static boolean chkNetworkStatus(Context context) {
    boolean result = false;
    new Thread() {
        @Override
        public void run() {


           for(int i=0;i<3;i++){
           HttpGet requestForTest = new HttpGet("http://m.google.com");
           try {
                  new DefaultHttpClient().execute(requestForTest);
                  responded = true;
                } catch (Exception e) {
                    responded = false;
                }
           }
        }
    }.start();
    boolean isOnline = isOnline(context);
    if(responded && isOnline){
        result = true;
    } else {
        result = false;
    }

    Log.e("","responded : "+responded);
    return result;
}

但在这种情况下,当我仍然连接到wifi并且我正在走路(失去连接)并按下同步按钮时它仍然返回true,因为我已连接,但实际上它没有做任何事情。

我是否可以检测到这一点,或者我应该在我正在使用的connectionTimeOut类中使用HttpURLConnection函数?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

实际上,我不知道这个问题是否可以解决您的问题,但您可以使用HttpGet请求设置连接超时,

这适用于我的情况,所以我不需要检查互联网的可用性..

try
  {

   HttpGet request = new HttpGet(url));
   HttpParams httpParameters = new BasicHttpParams();
   // Set the timeout in milliseconds until a connection is established.
   // The default value is zero, that means the timeout is not used. 
   int timeoutConnection = 60000;
   HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
   // Set the default socket timeout (SO_TIMEOUT) 
   // in milliseconds which is the timeout for waiting for data.
   int timeoutSocket = 60000;
   HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
   // create object of DefaultHttpClient    
   DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
   request.addHeader("Content-Type", "application/json");
   HttpResponse response = httpClient.execute(request);
   // get response entity
   HttpEntity entity = response.getEntity();
   // convert entity response to string

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

   }
 catch (SocketException e)
  {
     return "-222" + e.toString();
  }
 catch (Exception e)
  {
     return "-333" + e.toString();
  }

注意:请求和其他代码在您的情况下可能有所不同,它只是HttpGet参数如何用于设置连接TimeOut ..

答案 2 :(得分:1)

如果您注册网络连接,基本上您将收到广播。

android.net.conn.CONNECTIVITY_CHANGE

对于解决方案 你走了。

您需要注册并处理BroadCastReceiver android.net.conn.CONNECTIVITY_CHANGE

第1步

在清单

中加入以下权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<强>第二步

让Android知道哪个类将注册BroadCast Receiver。

<receiver android:name="ConnectivityReceiver_package_name.ConnectivityReceiver">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>

第3步

将您的逻辑用于各种网络状态。

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

     String action = intent.getAction();

    boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);

     if(noConnectivity){

         //Show Warning Message
         //Take appropriate actions.
     }

    }

}