Edalat Feizi
Edalat Feizi

Reputation: 1401

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 = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null) 
              for (int i = 0; i < info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
    }

getAllNetworkInfo(); was deprecated in api level 23 so i need a solution to check internet connection both api level 23 and prior,i found another way to do that

 private boolean isConnectedToInternet()
{
    ConnectivityManager cm = (ConnectivityManager) SplashActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null) { // connected to the internet
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                // connected to wifi
                Toast.makeText(SplashActivity.this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
                return true;
            } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
                // connected to the mobile provider's data plan
                Toast.makeText(SplashActivity.this, activeNetwork.getTypeName(), Toast.LENGTH_SHORT).show();
                return true;
            }
        } 
    return false;
}

my question is about getActiveNetworkInfo() and isConnected() the documentation provided by google for this method is here

Returns details about the currently active default data network. When connected, this network is the default route for outgoing connections. You should always check isConnected() before initiating network traffic. This may return null when there is no default network.

why we need to call isConnected() on getActiveNetworkInfo() for checking internet connection while we can check returned value from getActiveNetworkInfo() with null if not null we have internet connection else if returned null calling isConnected() on getActiveNetworkInfo() throws null pointer exception at runtime?

Upvotes: 1

Views: 8995

Answers (2)

Pasan Bhanu Guruge
Pasan Bhanu Guruge

Reputation: 286

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

Upvotes: 1

Ozgur
Ozgur

Reputation: 3766

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;

    }
}

Upvotes: 6

Related Questions