Rectangle 27 282

this method checks whether mobile is connected to internet and returns true if connected:

private boolean isNetworkConnected() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

  return cm.getActiveNetworkInfo() != null;
 }

in manifest,

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

Edit: This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

public boolean isInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
        }

    }

This answer is incorrect. If you're connected to a network that does not route to the internet this method will incorrectly return true. Note that getActiveNetworkInfo's javadoc says you should check NetworkInfo.isConnected(), but that is also not sufficient to check that you're on the internet. I'm looking into it further but you might have to ping a server on the internet to make sure you're actually on the internet.

be wary of isInternetAvailable() as it can fail on "network on main thread" exceptions and thus return false even when you have a connection.

isInternetAvailable() always return false for me. Even when bypassing the catch. I'm on 3G.

The first part works in the main thread, the second part (the edit) only works if not on the main thread.

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 282

this method checks whether mobile is connected to internet and returns true if connected:

private boolean isNetworkConnected() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

  return cm.getActiveNetworkInfo() != null;
 }

in manifest,

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

Edit: This method actually checks if device is connected to internet(There is a possibility it's connected to a network but not to internet).

public boolean isInternetAvailable() {
        try {
            InetAddress ipAddr = InetAddress.getByName("google.com"); //You can replace it with your name
            return !ipAddr.equals("");

        } catch (Exception e) {
            return false;
        }

    }

This answer is incorrect. If you're connected to a network that does not route to the internet this method will incorrectly return true. Note that getActiveNetworkInfo's javadoc says you should check NetworkInfo.isConnected(), but that is also not sufficient to check that you're on the internet. I'm looking into it further but you might have to ping a server on the internet to make sure you're actually on the internet.

be wary of isInternetAvailable() as it can fail on "network on main thread" exceptions and thus return false even when you have a connection.

isInternetAvailable() always return false for me. Even when bypassing the catch. I'm on 3G.

The first part works in the main thread, the second part (the edit) only works if not on the main thread.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 50

public boolean isNetworkAvailable(Context context) {
    final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
public boolean isInternetAvailable() {
    try {
        final InetAddress address = InetAddress.getByName("www.google.com");
        return !address.equals("");
    } catch (UnknownHostException e) {
        // Log error
    }
    return false;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How to find, connected to wifi but not actually active data on wifi.

Only tells you if you are connect to a network, and not the internet. If you want crashes (for internet safe code) then use this.

@Jared you ruined introducing the hell context

How is this different from the accepted answer?

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 50

public boolean isNetworkAvailable(Context context) {
    final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
public boolean isInternetAvailable() {
    try {
        final InetAddress address = InetAddress.getByName("www.google.com");
        return !address.equals("");
    } catch (UnknownHostException e) {
        // Log error
    }
    return false;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

How to find, connected to wifi but not actually active data on wifi.

Only tells you if you are connect to a network, and not the internet. If you want crashes (for internet safe code) then use this.

@Jared you ruined introducing the hell context

How is this different from the accepted answer?

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 28

You can simply ping an online website like google:

public boolean isConnected() throws InterruptedException, IOException
{
    String command = "ping -c 1 google.com";
    return (Runtime.getRuntime().exec (command).waitFor() == 0);
}

I think it's the smartest solution

Well @ZeeshanShabbir is right , a solar flare to the part of the country of google's main operation would take your application right out of the ball park , in such a scenario you could propably ping to a few addresses to check the same . Also , i think google wont be down if one center is down , a majority of them must be taken down for this to work also provided that your network operator survives the worldwide blackout :D

If your app relys on a remote server (for authentication, fetching data, communication with database.... etc) then you can use that server address instead of google, this way you can check for internet connectivity and the server availability at the same time. If your server is down and there is still an internet connection the app wont function properly anyways. In this case you might also want to set timeout interval for ping command using -i option like this ping -i 5 -c 1 www.myserver.com.

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 28

You can simply ping an online website like google:

public boolean isConnected() throws InterruptedException, IOException
{
    String command = "ping -c 1 google.com";
    return (Runtime.getRuntime().exec (command).waitFor() == 0);
}

I think it's the smartest solution

Well @ZeeshanShabbir is right , a solar flare to the part of the country of google's main operation would take your application right out of the ball park , in such a scenario you could propably ping to a few addresses to check the same . Also , i think google wont be down if one center is down , a majority of them must be taken down for this to work also provided that your network operator survives the worldwide blackout :D

If your app relys on a remote server (for authentication, fetching data, communication with database.... etc) then you can use that server address instead of google, this way you can check for internet connectivity and the server availability at the same time. If your server is down and there is still an internet connection the app wont function properly anyways. In this case you might also want to set timeout interval for ping command using -i option like this ping -i 5 -c 1 www.myserver.com.

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 21

The above methods work when you are connected to a Wi-Fi source or via cell phone data packs. But in case of Wi-Fi connection there are cases when you are further asked to Sign-In like in Cafe. So in that case your application will fail as you are connected to Wi-Fi source but not with the Internet.

public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
            urlc.setRequestProperty("User-Agent", "test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1000); // mTimeout is in seconds
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }
    }

    return false;

}

Please use this in a separate thread from the main thread as it makes a network call and will throw NetwrokOnMainThreadException if not followed.

And also do not put this method inside onCreate or any other method. Put it inside a class and access it.

This is a good approach to the problem. But probably a ping is enough

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 21

The above methods work when you are connected to a Wi-Fi source or via cell phone data packs. But in case of Wi-Fi connection there are cases when you are further asked to Sign-In like in Cafe. So in that case your application will fail as you are connected to Wi-Fi source but not with the Internet.

public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager)context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
        try {
            URL url = new URL("http://www.google.com/");
            HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
            urlc.setRequestProperty("User-Agent", "test");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1000); // mTimeout is in seconds
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            Log.i("warning", "Error checking internet connection", e);
            return false;
        }
    }

    return false;

}

Please use this in a separate thread from the main thread as it makes a network call and will throw NetwrokOnMainThreadException if not followed.

And also do not put this method inside onCreate or any other method. Put it inside a class and access it.

This is a good approach to the problem. But probably a ping is enough

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 14

private boolean checkInternetConnection() {
onCreate

you can create a thread to do continuous look up of network availability and let you know and keep retrying after an interval.

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 14

private boolean checkInternetConnection() {
onCreate

you can create a thread to do continuous look up of network availability and let you know and keep retrying after an interval.

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 13

The accepted answer's EDIT shows how to check if something on the internet can be reached. I had to wait too long for an answer when this was not the case (with a wifi that does NOT have an internet connection). Unfortunately InetAddress.getByName does not have a timeout parameter, so the next code works around that:

private boolean internetConnectionAvailable(int timeOut) {
    InetAddress inetAddress = null;
    try {
        Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
            @Override
            public InetAddress call() {
                try {
                    return InetAddress.getByName("google.com");
                } catch (UnknownHostException e) {
                    return null;
                }
            }
        });
        inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
        future.cancel(true);
    } catch (InterruptedException e) {
    } catch (ExecutionException e) {
    } catch (TimeoutException e) {
    } 
    return inetAddress!=null && !inetAddress.equals("");
}

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 13

The accepted answer's EDIT shows how to check if something on the internet can be reached. I had to wait too long for an answer when this was not the case (with a wifi that does NOT have an internet connection). Unfortunately InetAddress.getByName does not have a timeout parameter, so the next code works around that:

private boolean internetConnectionAvailable(int timeOut) {
    InetAddress inetAddress = null;
    try {
        Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
            @Override
            public InetAddress call() {
                try {
                    return InetAddress.getByName("google.com");
                } catch (UnknownHostException e) {
                    return null;
                }
            }
        });
        inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
        future.cancel(true);
    } catch (InterruptedException e) {
    } catch (ExecutionException e) {
    } catch (TimeoutException e) {
    } 
    return inetAddress!=null && !inetAddress.equals("");
}

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 4

public static boolean isNetworkAvailable(Context context) {
        boolean outcome = false;

        if (context != null) {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo[] networkInfos = cm.getAllNetworkInfo();

            for (NetworkInfo tempNetworkInfo : networkInfos) {


                /**
                 * Can also check if the user is in roaming
                 */
                if (tempNetworkInfo.isConnected()) {
                    outcome = true;
                    break;
                }
            }
        }

        return outcome;
    }

heres what I've got so far private boolean isNetworkConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni == null) { // There are no active networks. Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this,InfoActivity.class); TheEvoStikLeagueActivity.this.startActivity(connectionIntent); TheEvoStikLeagueActivity.this.finish(); return false; } else return true; }

Please try the piece of code I posted to check whether the device can connect to remote server or not...

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 4

public static boolean isNetworkAvailable(Context context) {
        boolean outcome = false;

        if (context != null) {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo[] networkInfos = cm.getAllNetworkInfo();

            for (NetworkInfo tempNetworkInfo : networkInfos) {


                /**
                 * Can also check if the user is in roaming
                 */
                if (tempNetworkInfo.isConnected()) {
                    outcome = true;
                    break;
                }
            }
        }

        return outcome;
    }

heres what I've got so far private boolean isNetworkConnected() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni == null) { // There are no active networks. Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this,InfoActivity.class); TheEvoStikLeagueActivity.this.startActivity(connectionIntent); TheEvoStikLeagueActivity.this.finish(); return false; } else return true; }

Please try the piece of code I posted to check whether the device can connect to remote server or not...

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 6

All official methods only tells weather device is open for network or not, If your device is connected to Wifi but Wifi is not connected to internet then these method will fail (Which happen many time), No inbuilt netwrok detection method will tell about this scenario, so created Async Callback class which will return in onConnectionSuccess and onConnectionFail

new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

            @Override
            public void onConnectionSuccess() {
   Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
            }

            @Override
            public void onConnectionFail(String msg) {
   Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
            }
        }).execute();
public class CheckNetworkConnection extends AsyncTask<Void, Void, Boolean> {
private OnConnectionCallback onConnectionCallback;
private Context context;

public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
     super();
     this.onConnectionCallback = onConnectionCallback;
    this.context = con;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params) {
    if (context == null)
        return false;

    boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
    return isConnected;
}

@Override
protected void onPostExecute(Boolean b) {
    super.onPostExecute(b);

    if (b) {
        onConnectionCallback.onConnectionSuccess();
    } else {
        String msg = "No Internet Connection";
        if (context == null)
            msg = "Context is null";
        onConnectionCallback.onConnectionFail(msg);
    }

}

public interface OnConnectionCallback {
    void onConnectionSuccess();

    void onConnectionFail(String errorMsg);
}
}
class NetWorkInfoUtility {

public boolean isWifiEnable() {
    return isWifiEnable;
}

public void setIsWifiEnable(boolean isWifiEnable) {
    this.isWifiEnable = isWifiEnable;
}

public boolean isMobileNetworkAvailable() {
    return isMobileNetworkAvailable;
}

public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
    this.isMobileNetworkAvailable = isMobileNetworkAvailable;
}

private boolean isWifiEnable = false;
private boolean isMobileNetworkAvailable = false;

public boolean isNetWorkAvailableNow(Context context) {
    boolean isNetworkAvailable = false;

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
    setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

    if (isWifiEnable() || isMobileNetworkAvailable()) {
        /*Sometime wifi is connected but service provider never connected to internet
        so cross check one more time*/
        if (isOnline())
            isNetworkAvailable = true;
    }

    return isNetworkAvailable;
}

public boolean isOnline() {
    /*Just to check Time delay*/
    long t = Calendar.getInstance().getTimeInMillis();

    Runtime runtime = Runtime.getRuntime();
    try {
        /*Pinging to Google server*/
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        long t2 = Calendar.getInstance().getTimeInMillis();
        Log.i("NetWork check Time", (t2 - t) + "");
    }
    return false;
 }
}

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 6

All official methods only tells weather device is open for network or not, If your device is connected to Wifi but Wifi is not connected to internet then these method will fail (Which happen many time), No inbuilt netwrok detection method will tell about this scenario, so created Async Callback class which will return in onConnectionSuccess and onConnectionFail

new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {

            @Override
            public void onConnectionSuccess() {
   Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
            }

            @Override
            public void onConnectionFail(String msg) {
   Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
            }
        }).execute();
public class CheckNetworkConnection extends AsyncTask<Void, Void, Boolean> {
private OnConnectionCallback onConnectionCallback;
private Context context;

public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
     super();
     this.onConnectionCallback = onConnectionCallback;
    this.context = con;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected Boolean doInBackground(Void... params) {
    if (context == null)
        return false;

    boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
    return isConnected;
}

@Override
protected void onPostExecute(Boolean b) {
    super.onPostExecute(b);

    if (b) {
        onConnectionCallback.onConnectionSuccess();
    } else {
        String msg = "No Internet Connection";
        if (context == null)
            msg = "Context is null";
        onConnectionCallback.onConnectionFail(msg);
    }

}

public interface OnConnectionCallback {
    void onConnectionSuccess();

    void onConnectionFail(String errorMsg);
}
}
class NetWorkInfoUtility {

public boolean isWifiEnable() {
    return isWifiEnable;
}

public void setIsWifiEnable(boolean isWifiEnable) {
    this.isWifiEnable = isWifiEnable;
}

public boolean isMobileNetworkAvailable() {
    return isMobileNetworkAvailable;
}

public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
    this.isMobileNetworkAvailable = isMobileNetworkAvailable;
}

private boolean isWifiEnable = false;
private boolean isMobileNetworkAvailable = false;

public boolean isNetWorkAvailableNow(Context context) {
    boolean isNetworkAvailable = false;

    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
    setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());

    if (isWifiEnable() || isMobileNetworkAvailable()) {
        /*Sometime wifi is connected but service provider never connected to internet
        so cross check one more time*/
        if (isOnline())
            isNetworkAvailable = true;
    }

    return isNetworkAvailable;
}

public boolean isOnline() {
    /*Just to check Time delay*/
    long t = Calendar.getInstance().getTimeInMillis();

    Runtime runtime = Runtime.getRuntime();
    try {
        /*Pinging to Google server*/
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        long t2 = Calendar.getInstance().getTimeInMillis();
        Log.i("NetWork check Time", (t2 - t) + "");
    }
    return false;
 }
}

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 5

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

duplicate and inaccurately returns true with a non-internet routing connection

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 5

public static boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

duplicate and inaccurately returns true with a non-internet routing connection

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 8

You can use following snippet to check Internet Connection.

It will useful both way that you can check which Type of NETWORK Connection is available so you can do your process on that way.

You just have to copy following class and paste directly in your package.

/**
 * 
 * @author Pratik Butani
 * 
 */
public class InternetConnection {

    /** CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT */
    public static boolean checkConnection(Context context) {
        final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();

        if (activeNetworkInfo != null) { // connected to the internet
            Toast.makeText(context, activeNetworkInfo.getTypeName(), Toast.LENGTH_SHORT).show();

            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                return true;
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                return true;
            }
        }
        return false;
    }
}

Now you can use like:

if (InternetConnection.checkConnection(context)) {
    // Its Available...
} else {
    // Not Available...
}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

You can modify based on your requirement.

networking - Android check internet connection - Stack Overflow

android networking android-networking
Rectangle 27 8

You can use following snippet to check Internet Connection.

It will useful both way that you can check which Type of NETWORK Connection is available so you can do your process on that way.

You just have to copy following class and paste directly in your package.

/**
 * 
 * @author Pratik Butani
 * 
 */
public class InternetConnection {

    /** CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT */
    public static boolean checkConnection(Context context) {
        final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();

        if (activeNetworkInfo != null) { // connected to the internet
            Toast.makeText(context, activeNetworkInfo.getTypeName(), Toast.LENGTH_SHORT).show();

            if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                return true;
            } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                return true;
            }
        }
        return false;
    }
}

Now you can use like:

if (InternetConnection.checkConnection(context)) {
    // Its Available...
} else {
    // Not Available...
}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

You can modify based on your requirement.

networking - Android check internet connection - Stack Overflow

android networking android-networking