2

I am trying to check working internet connection (not wifi connected). I tried the below code to check if response is 200.

    final int CONNECTION_TIMEOUT = 2000;
    try 
    {
        HttpURLConnection mURLConnection = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
        mURLConnection.setRequestProperty("User-Agent", "ConnectionTest");
        mURLConnection.setRequestProperty("Connection", "close");
        mURLConnection.setConnectTimeout(CONNECTION_TIMEOUT);
        mURLConnection.setReadTimeout(CONNECTION_TIMEOUT);
        mURLConnection.connect();
        return (mURLConnection.getResponseCode() == 200);
    } 
    catch (IOException ioe) 
    {
        Log.e("isInternetConnected", "Exception occured while checking for Internet connection: ", ioe);
    }
    return false;

I am calling the above method inside Async.

class checkInternet extends AsyncTask<String, String, String> 
{
    @Override
    protected String doInBackground(String... params) 
    {
        internetavailable = isInternetConnected();
        return null;
    }
}

I get the correct results, but when there is no internet it is taking more than one minute to send me "NO INTERNET" information. Is this usual or is there a faster way to get the results?

halfer
  • 19,824
  • 17
  • 99
  • 186
TheDevMan
  • 5,914
  • 12
  • 74
  • 144

4 Answers4

1

Don't use this method to check internet. because everytime when you check for connection it will try to open your given URL e.g. www.google.com. so if you are connected to data connection or in slow network. than it will take more time to call your service and your app will resond late every time you call any service.

You have to set Connection TimeOut for your request. so you can identify if connection is not properly.

use this to check connection.

follow this answer for Connection TimeOut

Community
  • 1
  • 1
Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75
  • Kachela = I am not looking for wifi connectivity. I am looking for Internet connectivity. The result shows True even though there is no internet because I have connected to wifi (router) and not to the internet. – TheDevMan Jul 08 '14 at 02:42
  • I didn't understand? Can you explain? Thanks! – TheDevMan Jul 08 '14 at 07:38
1

The time taken by your method depends entirely on the connection timeout you have set. A faster and recommended alternative to check if a connection is available is to use this function :

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

You can call it in your activity or async task by using isNetworkAvailable(this)

Please note this will not check if the internet connection actually works or not.

faizal
  • 3,497
  • 7
  • 37
  • 62
0

You can use ConnectivityManager to check network:

public boolean isInternetAvailable(Context c) {
    ConnectivityManager connectivity = (ConnectivityManager)c.getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivity !=null){
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null) {
            for (int i = 0; i < info.length; i++) {
                if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
    }
    return false;
}

Do not forget to add android.permission.ACCESS_NETWORK_STATE permission to AndroidManifest.xml.

ahsanul_k
  • 161
  • 8
0

You can use traffic stats to see if bytes are being received. Create one thread to continuously update number of bytes received and another to see if the number of bytes are increasing.

If it's increasing, your are online, else offline. Also, do check for the UNSUPPORTED value! See the code below:

startRX = TrafficStats.getTotalRxBytes();
startTX = TrafficStats.getTotalTxBytes();

if (startRX == TrafficStats.UNSUPPORTED || startTX == TrafficStats.UNSUPPORTED){
    Toast.makeText(getApplicationContext(),"This device doesn't support network API's!",Toast.LENGTH_LONG).show();
    //finish your activity here
}

currentMobileRX = TrafficStats.getMobileRxBytes();
currentWifiRX = TrafficStats.getTotalRxBytes() - TrafficStats.getMobileRxBytes();
halfer
  • 19,824
  • 17
  • 99
  • 186
Prasad Pawar
  • 1,606
  • 1
  • 15
  • 30