2

I have tried with the following function to test Internet availability :

public boolean isNetworkAvailable(){
        ConnectivityManager conn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            Network net=conn.getActiveNetwork();
            NetworkCapabilities nc=conn.getNetworkCapabilities(net);
            if(net==null){
                return  false;
            }else{
                return true;
            }}
        return false;
    }

It works great, but in the case the mobile doesn't have internet and mobile data is enabled the Application keeps crushing. So if someone tried resolving this issue please show me how. I'm working on my first Android project. I have tested some solutions from here: how to check internet connection is available, but it still not working.

thanks for replying !

1 Answers1

1

In order to check whether your device is connected to the internet or not use the below method which returns true if your device is connected to the internet.

This supports both WiFi and mobile data.

public boolean isOnline(Context context) {

    boolean isConnected = false;
    ConnectivityManager   mConnectivityMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
        // Checking internet connectivity
        NetworkInfo activeNetwork = null;
        if (mConnectivityMgr != null) {
            activeNetwork = mConnectivityMgr.getActiveNetworkInfo(); // Deprecated in API 29
        }
        isConnected = activeNetwork != null;

    } else {
        Network[] allNetworks = mConnectivityMgr.getAllNetworks(); // added in API 21 (Lollipop)

        for (Network network : allNetworks) {
            NetworkCapabilities networkCapabilities = mConnectivityMgr.getNetworkCapabilities(network);
            if (networkCapabilities != null) {
                if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
                        || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
                        || networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET))
                    isConnected = true;
            }
        }
    }

    return isConnected;

}

You can also have a look at this answer for more internet functionalities

Zain
  • 37,492
  • 7
  • 60
  • 84