2

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

    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

4

3 回答 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);
于 2012-06-14T12:38:38.807 回答
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参数如何用于设置连接超时的想法。

于 2012-06-14T12:42:53.687 回答
1

基本上,如果您注册,您将在网络连接发生变化时收到广播。

android.net.conn.CONNECTIVITY_CHANGE

解决方案给你。

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

第1步

在清单中包含以下权限

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

第2步

让 Android 知道哪个类将注册广播接收器。

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

    }

}
于 2012-06-14T12:43:40.943 回答