开发者

Checking if programm has the internet over wifi

After reading some answers and trying to use them I still can not make my code return a correct state, if there is internet over wifi or not开发者_StackOverflow中文版.

I must "ping" over WIFI, because we may be connected to the Access Point with no further internet connection. Here is a complete code.

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

is here lookupHost, suggested by another user :

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 is always false. I feel like the answer is in one step, but still don't know, what to do.

PS Sorry for my English.


This is the code I use and it works with no issues:

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

and the following in my manifest:

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

Note that on the emulated the detected internet connection can behave oddly.


My answer is :

    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) {
                }}}}}

Just to check, if the current connection is WIFI and then request a page, checking first character.


I got it work :)

First it's not allowed and it's not good to do httprequest on main thread! So you must do it in AsyncTask!

Second you don't need to check if there is connection or no... because you can be connected to local connection or too slow connection!

All you need is to do http request and check if there is response in the exact time. For that you need to set timeout! But only timeout is not working - you need to check the status code... here it is:

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

}

so now the json parser :)

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;

}
}

It works great!


try this method to check if there is a connection internet or not :

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

NOTE : you should have the permission of INTERNET in your manifest

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜