Skip to content Skip to sidebar Skip to footer

Checking Internet Connection In Android Using GetActiveNetworkInfo

if you want to check internet connection in android there is a lot of ways to do that for example: public boolean isConnectingToInternet(){ ConnectivityManager connectivity

Solution 1:

Use my util class:

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

/**
 * Created by ozgur on 16.04.2016.
 */
public class Utils {

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

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {

            Network[] activeNetworks = cm.getAllNetworks();
            for (Network n: activeNetworks) {
                NetworkInfo nInfo = cm.getNetworkInfo(n);
                if(nInfo.isConnected())
                    return true;
            }

        } else {
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null)
                for (NetworkInfo anInfo : info)
                    if (anInfo.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }

        return false;

    }
}

Solution 2:

Network info in deprecated. Use network callback. This is the method.

public void registerNetworkCallback()
{
    try {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = new NetworkRequest.Builder();

        connectivityManager.registerNetworkCallback(builder.build(),new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(Network network) {
                        Variables.isNetworkConnected = true; // Global Static Variable
                    }
                    @Override
                    public void onLost(Network network) {
                        Variables.isNetworkConnected = false; // Global Static Variable
                    }
                }

        );
        Variables.isNetworkConnected = false;
    }catch (Exception e){
        Variables.isNetworkConnected = false;
    }
}

Please check the full code here : Gist


Post a Comment for "Checking Internet Connection In Android Using GetActiveNetworkInfo"