Search code examples
androidconnectionhttpconnection

checking internet connection on android programming


I try to write an android program to check internet connection with two different methods. The first one is the most common method, CheckInternetConnection(), and the second method is through connecting to a website, ConnectGoogleTest(). The first one work perfectly, but in the second one my tablet hang! anybody knows why ?

The codes are:

public class myITClass {
private Context ctx ;
public myITClass(Context context){
    this.ctx = context;
}

public boolean CheckInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    //NetworkInfo ni = cm.getActiveNetworkInfo();
    if (cm.getActiveNetworkInfo() == null) {
        // There are no active networks.
        return false;
    } else {

        return true;
    }
  }
public boolean googlePingTest(){
    boolean res = false ;
    try {
        URL url = new URL("http://www.google.com/");
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setConnectTimeout(15000);
        urlc.connect();
        if (urlc.getResponseCode() == 200) { res = true; }
    } catch (MalformedURLException e1) {
        res = false;
    } catch (IOException e) {
        res = false ;
    }catch (Exception e){
        res = false ;
    }

    return res;
}
}

Solution

  • You can send a ping to http://www.google.com/ through HttpURLConnection. Please make sure that you doing it in the background thread. Creating a network task must be run in the background. There are 3 options to do that:

    In this time, we will use AsyncTask. So create a private class inside your Activity:

    private boolean res = false;
    private class PingTask extends AsyncTask<String, String, String> {
    
        @Override
        protected String doInBackground(String... urlSite) {
            HttpURLConnection urlc = null;
    
            try {
              URL url = new URL("http://www.google.com/");
              urlc = (HttpURLConnection) url.openConnection();
              urlc.setConnectTimeout(15000);
              urlc.setRequestMethod("GET");
              urlc.connect();
    
             if (urlc.getResponseCode() == 200) { res = true; }
          } catch (MalformedURLException e1) {
             res = false;
          } catch (IOException e) {
             res = false ;
          }catch (Exception e){
             res = false ;
          }finally{
                if (urlc != null) {
                    try{
                        // close the connection
                        urlc.disconnect();
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
            return null;
         }
    }
    

    Don't forget to add this field in your class:

    private boolean res = false;
    

    Create a method to get the status:

    public boolean getStatus(){
        return status;
    }
    

    How to use?

    Execute the PingTask first to check the status:

    PingTask ping = new PingTask();
    ping.execute();
    

    Get the status:

    // if the connection is available
    if(getStatus()==true){
        // do your thing here.
    }