'Android - Programmatically check internet connection and display dialog if notConnected

I am working on a live project. and when user click on the app. the welcome screen appears(there is a webview on that screen). and if the internet is not connected then the app crashes. Basically, my problem is to check programmatically that is mobile is connected to internet or not. if not then don't fetch the data from webservice into webview and display a dialog box showing "Check your internet connection"

while doing research i found many things, and i have tried to implement that. but, its not satisfying my requirement

my code is,

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    else
    {
        Description.setVisibility(View.INVISIBLE);
        new AlertDialog.Builder(WelcomePage.this)
        .setTitle(getResources().getString(R.string.app_name))
        .setMessage(
                getResources().getString(
                        R.string.internet_error))
        .setPositiveButton("OK", null).show();
    }
    return false;
}

i am calling this function in doInBackground() of AsyncTask

Please Help!



Solution 1:[1]

Finally, I got the answer.

ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null){
    Description.setVisibility(View.INVISIBLE);
    new AlertDialog.Builder(WelcomePage.this)
        .setTitle(getResources().getString(R.string.app_name))
        .setMessage(getResources().getString(R.string.internet_error))
        .setPositiveButton("OK", null).show();
}else{
    dialog = ProgressDialog.show(WelcomePage.this, "", "Loading...", true,false);
    new Welcome_Page().execute();
}

Solution 2:[2]

You could checkout this library:

https://github.com/novoda/merlin

You just implement Connectable and you will get a callback when the network goes down or comes up.

Therefore you can show your dialog in this scenario.

You can also query the library for the current state and choose not to do your network task

example

Create Merlin (using Merlin.Builder())

merlin = new Merlin.Builder().withConnectableCallbacks().build(context);

Bind and unbind the service in your activity

@Override
protected void onResume() {
    super.onResume();
    merlin.bind();
}

@Override
protected void onPause() {
    super.onPause();
    merlin.unbind();
}

Register for callbacks

merlin.registerConnectable(new Connectable() {
        @Override
        public void onConnect() {
            // Do something!
        }
});

The MerlinActivity within the demo shows a simple way to declutter Merlin from your main application code.

Solution 3:[3]

NetworkInfo class is deprecated in API 29 (Android 10.0) for more detail see here:

This class was deprecated in API level 29. Use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to get information synchronously

Updated Code (with Kotlin)

var isConnected = false
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    val activeNetwork = connectivityManager.activeNetwork ?: return false
    val networkCapabilities = connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
    isConnected = when {
        activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
        activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
        activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
        else -> false
    }
} else {
    isConnected = when (connectivityManager.activeNetworkInfo?.type) {
        ConnectivityManager.TYPE_WIFI -> true
        ConnectivityManager.TYPE_MOBILE -> true
        ConnectivityManager.TYPE_ETHERNET -> true
        else -> false
    }
}

Solution 4:[4]

Check internet connection

 ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo netInfo = mgr.getActiveNetworkInfo();

        if (netInfo != null) {
            if (netInfo.isConnected()) {
                // Internet Available
            }else {
               //No internet
            }
        } else {
            //No internet
        }

Solution 5:[5]

This is simple function that check your Internet connection. If Connected return true otherwise false.

 public boolean isInternetOn() {

        // get Connectivity Manager object to check connection
        ConnectivityManager connec =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        // Check for network connections
        if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {


            return true;

        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {


            return false;
        }
        return false;
    }
}

Here's a project that check internet connection and also check url that valid or contain in sever this.

Solution 6:[6]

if (InternetConnection.checkConnection(context)) {
    // Internet Available...
} else {
    // Internet Not Available...
}

just copy below class

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

Give following permission to manifest

<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" />

Solution 7:[7]

I've tried different methods described above, besides it I've been caught in some cases. So finally, I'm using below code snippet to make a network call...

try {
    InetAddress address = InetAddress.getByName("www.stackoverflow.com");
    //Connected to working internet connection
} catch (UnknownHostException e) {
    e.printStackTrace();
    //Internet not available
}

This can be useful in many perspectives. If something is not fine in this approach, please let me know.

Solution 8:[8]

 public boolean isOnline() {
        NetworkInfo activeNetworkInfo = ((ConnectivityManager) 
        getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return activeNetworkInfo != null && 
        activeNetworkInfo.isConnectedOrConnecting();
    }

Solution 9:[9]

The fact the your device has network connectivity doesn't mean that you can access internet. It can be a wifi without internet or a data SIM without data package. Starting from API 23 you can use below to check it. You can do it on the UI. Or within a broadcast receiver.

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
Network currentnetwork = cm.getActiveNetwork();
if (currentnetwork != null) {
        if (cm.getNetworkCapabilities(currentnetwork).hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && cm.getNetworkCapabilities(currentnetwork).hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
            
            // do your stuff. We have internet.
    } else {
            // We have no internet connection.
        }

   } else {
       // We have no internet connection.
   }

Solution 10:[10]

private boolean isOnline() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnected());
    }

This is the official way, Google also uses this same way to check the internet connection of the android device. You can check here - link. This is a very perfect way, it actually checks if the internet is working or not.

Now your specific problem, Use a timer class then put a toast in that if(isOnline) then toast.

Solution 11:[11]

doInBackground runs on a different Thread than the main UI, so you can't create a show a dialog here. Instead, override onPreExecute in your AsyncTask, and do the test there.

Solution 12:[12]

An Updated Kotlin and Android 29 Version (getNetworkInfo is deprecated in SDK 29) on how to check for internet connection, works for minSDK >= 23 :

fun hasInternet(): Boolean {
    val connectivityManager = appContainer.contextProvider.currentAppContext()
        .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val network = connectivityManager.activeNetwork

    val capabilities = connectivityManager.getNetworkCapabilities(network)
    var hasInternet = false
    capabilities?.let {
        hasInternet = it.hasCapability(NET_CAPABILITY_INTERNET)
    }
    return hasInternet
}

Solution 13:[13]

This cup of code helps you to check internet connection available or not from the API level 16 to 30

@SuppressWarnings("deprecation")
public static boolean isInternetAvailable(Activity activity) {
    ConnectivityManager conMgr = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        Network network = conMgr.getActiveNetwork();
        NetworkCapabilities networkCapabilities = conMgr.getNetworkCapabilities(network);
        if (networkCapabilities != null) {
            return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
        } else return false;
    } else {
        // below API Level 23
        return conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected();
    }
}