Android - Programmatically check internet connection and display dialog if notConnected
Asked Answered
D

14

33

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!

Dextrose answered 26/7, 2013 at 11:35 Comment(1)
Does this check internet connection or wifi connection. I suspect the latter, and that internet connection can only be verified by a ping?Daly
D
21

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();
}
Dextrose answered 1/8, 2013 at 12:43 Comment(3)
this shouldn't be the expected answer as you yourself asked how to check Internet connectivity and not network connectivity and the above answer shows the latter partToffic
This will execute Welcome_Page() if device is connected to network but has no data (internet) balance to useSuiting
You have to be careful because Internet connection is not the same as network connection. I'd strongly recommend you to use something solid like https://mcmap.net/q/440101/-android-programmatically-check-internet-connection-and-display-dialog-if-notconnected, or check the sourcecodeScleroderma
S
30

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.

Schliemann answered 26/7, 2013 at 11:56 Comment(3)
if you goto github.com/novoda/merlin and scroll down, read the read me, it explains it very simplySchliemann
merlin keeps leaking everytime i finish second activity with merlin (first is using it too) (I do have merlin.unbind and merlin == null in onPause and in onDestroy)Multiped
@KrzysztofDziuba we'll be happy to help you with Merlin if you open an issue on the GH repo github.com/novoda/merlin/issuesTearjerker
D
21

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();
}
Dextrose answered 1/8, 2013 at 12:43 Comment(3)
this shouldn't be the expected answer as you yourself asked how to check Internet connectivity and not network connectivity and the above answer shows the latter partToffic
This will execute Welcome_Page() if device is connected to network but has no data (internet) balance to useSuiting
You have to be careful because Internet connection is not the same as network connection. I'd strongly recommend you to use something solid like https://mcmap.net/q/440101/-android-programmatically-check-internet-connection-and-display-dialog-if-notconnected, or check the sourcecodeScleroderma
H
15

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
    }
}
Habitable answered 16/1, 2020 at 17:27 Comment(1)
update as : val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> trueCantata
C
12

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
        }
Creak answered 26/4, 2017 at 12:35 Comment(0)
C
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.

Concertgoer answered 5/5, 2016 at 6:51 Comment(0)
P
3
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" />
Poirier answered 28/3, 2018 at 7:51 Comment(0)
S
2

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.

Suiting answered 20/7, 2016 at 5:27 Comment(3)
This works but have to be executed in worker thread. The above code gives Network on main thread exception.Instrumental
Agreed @SkyTreasure, It's up to how we make use of this snippet ;)Suiting
@Instrumental would you give the code of using it with a thread with the main thread?Computation
E
1
 public boolean isOnline() {
        NetworkInfo activeNetworkInfo = ((ConnectivityManager) 
        getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return activeNetworkInfo != null && 
        activeNetworkInfo.isConnectedOrConnecting();
    }
Erythema answered 24/7, 2019 at 12:8 Comment(0)
Y
1

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
}
Youngran answered 11/8, 2020 at 12:10 Comment(0)
S
1
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.

Sanctimony answered 4/9, 2020 at 9:32 Comment(0)
S
1

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.
   }
Serrulation answered 18/9, 2020 at 8:43 Comment(0)
E
1

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();
    }
}
Emporium answered 6/10, 2020 at 11:58 Comment(0)
C
0

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.

Cronus answered 26/7, 2013 at 11:38 Comment(3)
@Dextrose it look good to me - it just needs to be moved to a different method (one that runs in the UI thread).Cronus
@Dextrose please read my answer. You need to do this in onPreExecute, which you can override in your AsyncTask. Follow the provided link to get more help on that.Cronus
@Phil..Buddy, i tried that also...its neither working in 'onCreate' of main thread nor in 'onPreExecute' of 'AsyncTask'Dextrose
S
-3

Internet connection also check either in onCreate() or onResume() method. There is no need to call inside the AsyncTask.

or You can call before call the AsyncTask execute() method

if(isOnline)
{
   MyAsyncTask task=new MyAMyAsyncTask();
   task.execute();

}

else
{
// no internet connection
}
Serafinaserafine answered 26/7, 2013 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.