Check internet connection in android (not network connection)

4.6k views Asked by At

I have a problem with checking internet connection in android at runtime. I use some different methods to check internet connection but i don't know which one is better . because each of them have some problems .

Method 1 check internet connection by pinging Google :

Runtime runtime = Runtime.getRuntime();
try {
       Process mIpAddressProcess = runtime.exec("/system/bin/ping -c 1   8.8.8.8");
       int mExitValue = mIpAddressProcess.waitFor();
       return mExitValue == 0;
} catch (InterruptedException | IOException ignore) {
            ignore.printStackTrace();
}

Method 2 check internet connection by ConnectivityManager :

public boolean checkNetwork() {

    ConnectivityManager internetManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = internetManager.getActiveNetworkInfo();
    return (networkInfo != null && networkInfo.isConnected() && networkInfo.isAvailable() && networkInfo.isConnectedOrConnecting());

}

I use method 1 inside an async task, but it doesn't work correctly sometimes and slow down the app, and Method 2 (ConnectivityManager) doesn't check internet connection , it checks only network connection !

7

There are 7 answers

5
W4R10CK On BEST ANSWER

I'm using broadcast to check the connection every time. Create a class for connection info.

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


public class ConnectivityStatus extends ContextWrapper{

    public ConnectivityStatus(Context base) {
        super(base);
    }

    public static boolean isConnected(Context context){

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo connection = manager.getActiveNetworkInfo();
        if (connection != null && connection.isConnectedOrConnecting()){
            return true;
        }
        return false;
    }
}

Apply code into your Activity:

 private BroadcastReceiver receiver = new BroadcastReceiver() {
 @Override
 public void onReceive(Context context, Intent intent) {
        if(!ConnectivityStatus.isConnected(getContext())){
            // no connection
        }else {
            // connected
        }
    }
 };

Register broadcast in your activity's onCreate() method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    ..
    ...
    ....
  }

Don't forget to unregistered/register on Activity cycle:

@Override
protected void onResume() {
    super.onResume();
    your_activity_context.registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

}

@Override
protected void onPause() {
    super.onPause();
    your_activity_context.unregisterReceiver(receiver);

}
0
eLemEnt On
public static boolean isNetworkAvailable(Context context) {
    try {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService
                (Context.CONNECTIVITY_SERVICE);
        if (connManager.getActiveNetworkInfo() != null && connManager.getActiveNetworkInfo()
                .isAvailable() && connManager.getActiveNetworkInfo().isConnected()) {
            return true;
        }
    } catch (Exception ex) {

        ex.printStackTrace();
        return false;
    }
    return false;
}

then just call this function from your fragment or Activity will work

0
Piyush On

This is what i try in android to check internet connection it is not sleek solution but does the work given you have already checked for the network :

try {
      HttpURLConnection urlConnection = (HttpURLConnection)
      (new URL("http://clients3.google.com/generate_204")
      .openConnection());
      urlConnection.setRequestProperty("User-Agent", "Android");
      urlConnection.setRequestProperty("Connection", "close");
      urlConnection.setConnectTimeout(1500);
      urlConnection.connect();
      if (urlConnection.getResponseCode() == 204 &&
      urlConnection.getContentLength() == 0) {
      Log.d("Network Checker", "Successfully connected to internet");
      return true;
      }
      } catch (IOException e) {
      Log.e("Network Checker", "Error checking internet connection", e);
      }

It's accurate for me.Try and let me know if you find any other good solution.

0
Hasif Seyd On

To check if internet connection is available or not, you can use the below code snippet

    public static boolean hasActiveInternetConnection(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) 
                    (new URL("http://clients3.google.com/generate_204")
                    .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 204 && urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(LOG_TAG, "No network available!");
    }
    return false;
}

This code snippet will also help you to identify whether you device is having internet connection even if you are connected through wifi network.

Note: make sure to call this method in background thread ,because this can take time depending on your network speed, and should not be called in Main thread

0
Ashish Gupta On

Just check this LINK Here is the answer for both Connection & Internet.

0
Sunil Chaudhary On

You can do it like this

uses-permission android:name="android.permission.INTERNET"

uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"

 private boolean checkInternet(Context context) {
    // get Connectivity Manager object to check connection
    ConnectivityManager connec
            =(ConnectivityManager)context.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 ) {
        Toast.makeText(context, " Connected ", Toast.LENGTH_LONG).show();
        return true;
    }else if (
            connec.getNetworkInfo(0).getState() ==
                    android.net.NetworkInfo.State.DISCONNECTED ||
                    connec.getNetworkInfo(1).getState() ==
                            android.net.NetworkInfo.State.DISCONNECTED  ) {
        Toast.makeText(context, " Not Connected ", Toast.LENGTH_LONG).show();
        return false;
    }
    return false;
}
0
saiRam89 On

You can use below code to check whether network connection is available or not.

public class NetworkConnection {
    public Context context;

    public NetworkConnection(Context applicationContext) {
        this.context=applicationContext;
    }

    public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }
}

public class MainActivity extends AppCompatActivity {
    NetworkConnection nt_check;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        nt_check=new NetworkConnection(context);
        if(nt_check.isOnline()) {
            // do logic
        } else {
            // show message network is not available.
        }
    }
}