【问题标题】:Checking if programm has the internet over wifi检查程序是否通过 wifi 上网
【发布时间】:2011-05-29 10:20:22
【问题描述】:

在阅读了一些答案并尝试使用它们后,我仍然无法让我的代码返回正确的状态,无论是否有通过 wifi 连接的互联网。

我必须通过 WIFI “ping”,因为我们可能连接到接入点而没有进一步的互联网连接。这是完整的代码。

ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NI = CM.getActiveNetworkInfo();
boolean IC = false;             
IC = CM.requestRouteToHost(ConnectivityManager.TYPE_WIFI, FlavaGr.lookupHost(pingyIp));
System.out.println("##### IC=" + IC + "  TYPE = " + NI.getTypeName());

这里是另一个用户建议的lookupHost:

public static int lookupHost(String hostname) {
InetAddress inetAddress;
try {
    inetAddress = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
    return -1;
}
byte[] addrBytes;
int addr;
addrBytes = inetAddress.getAddress();
addr = ((addrBytes[3] & 0xff) << 24)
        | ((addrBytes[2] & 0xff) << 16)
        | ((addrBytes[1] & 0xff) << 8)
        |  (addrBytes[0] & 0xff);
return addr;
}   

IC 总是假的。 我觉得答案是一步到位,但仍然不知道该怎么做。

PS 对不起我的英语。

【问题讨论】:

    标签: android android-wifi


    【解决方案1】:

    这是我使用的代码,它没有任何问题:

        ConnectivityManager conn;
                conn=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                // Skip if no connection, or background data disabled
                NetworkInfo info = conn.getActiveNetworkInfo();
                if (info == null ||
                !conn.getBackgroundDataSetting()) {
                    // No Network detected
                    return;
                } else {
                    int netType = info.getType();
                    int netSubtype = info.getSubtype();
                    if (netType == ConnectivityManager.TYPE_WIFI) {
                        //WIFI DETECTED
                                  } else if (netType == ConnectivityManager.TYPE_MOBILE
                    && netSubtype >2) {
                               //Mobile connected that is at least 3G   
                    } else {
                        //Has connection but i'm not sure what kind
                    }
                }
    

    以及我的清单中的以下内容:

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

    请注意,在仿真器上检测到的互联网连接可能表现异常。

    【讨论】:

      【解决方案2】:

      我的答案是:

          ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo NI = CM.getActiveNetworkInfo();
          if (NI!=null) {
              if (NI.isAvailable()) { 
                  boolean IC = false;
                  if (NI.getTypeName()=="WIFI") {
                      int response = 0;
                      try {
                          URL url = new URL("http://www.google.com/");    
                          BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                          response = in.read();
                          in.close();
      
                          IC = (response != -1) ? true : false;
                          System.out.println("##### IC=" + IC + "  TYPE = " + NI.getTypeName() + "  response = " + response);
                          if (true){
                                                      ;
                          };
                      } catch (Exception e) {
                      }}}}}
      

      只是检查,如果当前连接是WIFI,然后请求一个页面,检查第一个字符。

      【讨论】:

      • 为什么要检查第一个字符?
      • 更重要的是,您如何知道您是通过 wifi 而不是 3G 连接的?
      • 这仅告诉您您已连接到 WiFi。如果您有没有互联网连接的 wifi,它将使用 3G 连接...
      • ^ 它只能返回 1 个值。
      • 如果您连接到没有互联网访问的 WiFi 网络,它不会返回 NI.getTypeName()=="WIFI" => true 吗?
      【解决方案3】:

      我搞定了:)

      首先是不允许的,而且在主线程上做httprequest也不好!所以必须在 AsyncTask 中完成!

      其次你不需要检查是否有连接...因为你可以连接到本地连接或连接太慢!

      您只需要进行http请求并检查是否在准确的时间有响应。为此,您需要设置超时!但只有超时不起作用 - 您需要检查状态代码...这里是:

      class ConnectionTask extends AsyncTask<String, String, String> {
      
          /**
           * Before starting background thread set flag to false
           * */
          @Override
          protected void onPreExecute() {
              super.onPreExecute();
              flag = false;
          }
      
          boolean flag;
      
          /**
           * getting All products from url
           * */
          protected String doInBackground(String... args) {
              // Building Parameters
              List<NameValuePair> params = new ArrayList<NameValuePair>();
              // getting JSON string from URL
              Log.v("url",url);
              JSONObject json = jParser.makeHttpRequest(url, "GET", params); 
              /*is json equal to null ?*/
              if( json != null )
              {
                  // Check your log cat for JSON response
                  Log.d("json: ", json.toString());
                  try {
                      message = json.getString("message");
                      flag = true;//we succeded so we make the flag to true
                  } catch (JSONException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }
              else
              {//if json is null
                  message = "not connected to internet connection";
                  flag = false;
              }
      
              return null;
          }
      
          /**
           * After completing background task check if there is connection or no
           * **/
          protected void onPostExecute(String file_url) {
              // updating UI from Background Thread
              if(flag)
              {//flag is tro so there is connection
                  Log.v("connection", "conectioOOOOOoooOooooOoooooOOOOoooOOOOOO");
                  runOnUiThread(new Runnable() {
                      public void run() {
                          /**
                           * Updating parsed JSON data into textview
                           * */
                          TextView tvTest = (TextView) findViewById(R.id.testTextView);
                          tvTest.setText(message);
                      }
                  });
              }
              else
              {////we catched that there is no connection!
                  Log.v("connection", "nooooooo conectioOOOOOoooOooooOoooooOOOOoooOOOOOO");
                  runOnUiThread(new Runnable() {
                      public void run() {
                                  /*update ui thread*/
                          TextView tvTest = (TextView) findViewById(R.id.testTextView);
                          tvTest.setText("no connection");
                          Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
                      }
                  });
              }
          }
      
      }
      

      所以现在是 json 解析器 :)

      public class JSONParser {
      
      private InputStream is = null;
      private JSONObject jObj = null;
      private String json = "";
      static int timeoutConnection = 10000;
      static int timeoutSocket = 10000;
      
      // constructor
      public JSONParser() {
      
      }
      
      // function get json from url
      // by making HTTP POST or GET method
      public JSONObject makeHttpRequest(String url, String method,
              List<NameValuePair> params) {
      
          // check for request method
          if(method == "POST"){
              try{
                 HttpPost request = new HttpPost(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. 
                 HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                 // Set the default socket timeout (SO_TIMEOUT) 
                 // in milliseconds which is the timeout for waiting for data.
                 HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
                 // create object of DefaultHttpClient    
                 DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
                 request.addHeader("Content-Type", "application/json");
                 HttpResponse response = httpClient.execute(request);
                  StatusLine statusLine = response.getStatusLine();
                  int statusCode = statusLine.getStatusCode();
                  if (statusCode == 200) {
                      HttpEntity entity = response.getEntity();
                     is = entity.getContent();
      
                  }
                 // convert entity response to string
      
             }
           catch (SocketException e)
            {
                e.printStackTrace();
               return null;
            }
           catch (Exception e)
            {
                e.printStackTrace();
               return null;
            }
      
          }else if(method == "GET"){
              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. 
                 HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                 // Set the default socket timeout (SO_TIMEOUT) 
                 // in milliseconds which is the timeout for waiting for data.
                 HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
                 // create object of DefaultHttpClient    
                 DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
                 request.addHeader("Content-Type", "application/json");
                 HttpResponse response = httpClient.execute(request);
                 StatusLine statusLine = response.getStatusLine();
                 int statusCode = statusLine.getStatusCode();
                 if (statusCode == 200) {
                     HttpEntity entity = response.getEntity();
                     is = entity.getContent();
      
                 }
                 // convert entity response to string
      
                 }
               catch (SocketException e)
                {
                   e.printStackTrace();
                   return null;
                }
               catch (Exception e)
                {
                   e.printStackTrace();
                   return null;
                }
          }
      
          try {
              BufferedReader reader = new BufferedReader(new InputStreamReader(
                      is, "iso-8859-1"), 8);
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null) {
                  sb.append(line + "\n");
              }
              is.close();
              json = sb.toString();
          } catch (Exception e) {
              Log.e("Buffer Error", "Error converting result " + e.toString());
          }
      
          // try parse the string to a JSON object
          try {
              jObj = new JSONObject(json);
          } catch (JSONException e) {
              Log.e("JSON Parser", "Error parsing data " + e.toString());
          }
      
          // return JSON String
          return jObj;
      
      }
      }
      

      效果很好!

      【讨论】:

        【解决方案4】:

        试试这个方法看看是否有网络连接:

        public boolean connexionStatus(ConnectivityManager connec)
            {
                NetworkInfo[] allNetwork = connec.getAllNetworkInfo();
                if (allNetwork != null) 
                {
                    for (int i = 0; i < allNetwork.length; i++) 
                    {
                        if (allNetwork[i].getState() == NetworkInfo.State.CONNECTED || 
                                allNetwork[i].getState() == NetworkInfo.State.CONNECTING )
                            return true;
                    }
                }
                return false;
            }
        

        注意:你应该在你的ma​​nifest

        中拥有INTERNET的permission

        【讨论】:

        • 如果与没有互联网连接的接入点有连接,它会起作用
        • 试试看,我想如果你连接到一个没有互联网连接的接入点,你可以设置你的连接超时
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-26
        • 1970-01-01
        • 2018-03-09
        • 1970-01-01
        • 1970-01-01
        • 2011-12-09
        相关资源
        最近更新 更多