Check Internet Connection in Android

In Android application we are generally doing so many network related task. so before doing the task which is related to network which must check internet connectivity first to increase the performance. we must not execute the connection related task without internet.

So here is code to check internet connection.


public boolean isConnected() {
    ConnectivityManager con =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = con.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

just use this method to check internet connection if it returns yes then do your network related task.


if (isConnected())
   // Do your network related stuff here
   Toast.makeText(MainActivity.this,"Connected", Toast.LENGTH_SHORT).show();
else
   Toast.makeText(MainActivity.this,"Not Connected",Toast.LENGTH_SHORT).show();

1 comment:

Pages