-1

I have searching for a fast and effective method to check the internet connection, and i found that its better to ping google to find the internet connection status.But I found a number of ways to ping google and i am confused which one to use out of all Those.Below are the methods that i saw.

Method 1 :

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

Method 2 :

public Boolean isOnline() {
    try {
        Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
        int returnVal = p1.waitFor();
        boolean reachable = (returnVal==0);
        return reachable;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

Method 3 :

public static boolean hasInternetAccess(Context context) {
if (isNetworkAvailable(context)) {
    try {
        HttpURLConnection urlc = (HttpURLConnection) 
            (new URL("http://clients3.google.com/generate_204")
            .openConnection());
        urlc.setRequestProperty("User-Agent", "Android");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500); 
        urlc.connect();
        return (urlc.getResponseCode() == 204 &&
                    urlc.getContentLength() == 0);
    } catch (IOException e) {
        Log.e(TAG, "Error checking internet connection", e);
    }
} else {
    Log.d(TAG, "No network available!");
}
return false;
}

Method 4 :

public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
    try {
        HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
        urlc.setRequestProperty("User-Agent", "Test");
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1500); 
        urlc.connect();
        return (urlc.getResponseCode() == 200);
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error checking internet connection", e);
    }
} else {
    Log.d(LOG_TAG, "No network available!");
}
return false;
}

Which one i should choose?? I need a faster and effective method.

Manohar
  • 22,116
  • 9
  • 108
  • 144
KJEjava48
  • 1,967
  • 7
  • 40
  • 69
  • 1
    Possible duplicate of [Check internet connection in android (not network connection)](http://stackoverflow.com/questions/41545504/check-internet-connection-in-android-not-network-connection) – W4R10CK Jan 11 '17 at 06:33
  • Refer this link for [Detect Internet Connection Status](http://www.androidhive.info/2012/07/android-detect-internet-connection-status/) – Pankaj Lilan Jan 11 '17 at 06:35
  • 1
    I'd say method 1 because that would bypass a need for a functional DNS server. Method 1 and 2 aren't really that different, though. – OneCricketeer Jan 11 '17 at 06:41
  • @cricket_007, does my method produce complexity checking connection on the app ? – W4R10CK Jan 11 '17 at 06:43
  • @W4R10CK It checks for network connectivity, not necessarily internet reachability – OneCricketeer Jan 11 '17 at 06:44
  • Ohk, Thats the answer OP wants to get. Thanks @cricket_007 – W4R10CK Jan 11 '17 at 06:46
  • @cricket_007 but sometimes method 1 gives false if internet is there.Is this bcos any time issues?? – KJEjava48 Jan 11 '17 at 06:50
  • @DavidRawson How?? Above are the methods for finding the active internet connection and all those will work, and i asked what will be the most effective solution as per the time taken to find the state and other parameters. – KJEjava48 Mar 17 '17 at 11:11

2 Answers2

0

You can try to check if host is available with InetAddress.getByName(host).isReachable(timeOut). It should be same as checking if connection is valid.

Check documentation for more info.InetAddress

Vygintas B
  • 1,624
  • 13
  • 31
-1

I'm using broadcast to check the connection every time. Create a class for connection info.

import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class ConnectivityStatus extends ContextWrapper{

    public ConnectivityStatus(Context base) {
        super(base);
    }

    public static boolean isConnected(Context context){

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo connection = manager.getActiveNetworkInfo();
        if (connection != null && connection.isConnectedOrConnecting()){
            return true;
        }
        return false;
    }
}

Apply code into your Activity:

 private BroadcastReceiver receiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
        if(!ConnectivityStatus.isConnected(getContext())){
            // no connection
        }else {
            // connected
        }
    }
 };

Register broadcast in your activity's onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    ..
    ...
    ....
  }

Don't forget to unregistered/register on Activity cycle:

@Override
protected void onResume() {
    super.onResume();
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

}

@Override
protected void onPause() {
    super.onPause();
    your_activity_context.unregisterReceiver(receiver);

}
W4R10CK
  • 5,502
  • 2
  • 19
  • 30
  • 2
    This only shows if wifi or mobile networks enabled. It doest show if internet connection is working. – KJEjava48 Jan 11 '17 at 06:34
  • 1
    It works very well, to check if the connection is available or not for continuously. One checks the connection and broadcast to your activity to notify the connection. This code is working very well in our 3 Apps on Google play store. – W4R10CK Jan 11 '17 at 06:36
  • @KJEjava48 did u try the method? – W4R10CK Jan 11 '17 at 06:54
  • No, as I said ur method will check whether there is a network or not.ConnectivityManager and NetworkInfo only check for the network not the internet connection.If we have access to a network that doesn't mean that we can can browse or use internet. – KJEjava48 Jan 11 '17 at 06:58