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.
 */publicclassUtils {

    publicstaticbooleanisConnected(Context context){
        ConnectivityManagercm= (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) {
                NetworkInfonInfo= cm.getNetworkInfo(n);
                if(nInfo.isConnected())
                    returntrue;
            }

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

        returnfalse;

    }
}

Solution 2:

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

publicvoidregisterNetworkCallback()
{
    try {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkRequest.Builder builder = newNetworkRequest.Builder();

        connectivityManager.registerNetworkCallback(builder.build(),newConnectivityManager.NetworkCallback() {
                    @OverridepublicvoidonAvailable(Network network) {
                        Variables.isNetworkConnected = true; // Global Static Variable
                    }
                    @OverridepublicvoidonLost(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"