24

I have the following code for checking internet connection wifi/EDGE/GPRS/3G on my application.

the code is

public static boolean checkConn(Context ctx) {
    ConnectivityManager conMgr = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) {
        return true;
    } else if (conMgr.getNetworkInfo(0).getState()==NetworkInfo.State.DISCONNECTED
        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED){
        return false;
    }
    return false;
}

and I am calling it like below :

if (CheckInternet.checkConn(introPage.this) == true) {
    Intent toMainPage = new Intent(introPage.this, mainPage.class);
    System.gc();
    startActivity(toMainPage);
} else if (CheckInternet.checkConn(getApplicationContext()) == false) {
    Toast.makeText(getApplicationContext(),
        "Sorry, No internet connectivity found", Toast.LENGTH_SHORT)
            .show();
}

But I am having an issue, which is that if I am connected to wifi, and I open the application, it works fine, but if I close application and turn off wifi and re-open application, it doesn't through the error of "no connection" , I need to turn off my device and then turn it on, and same case is if wifi is off, and I open application, it throws error of "no connection", and if I turn it on, still it throws the same error of "no connection", until unless I turn off and on device.

Sam
  • 7,252
  • 16
  • 46
  • 65
Adil Bhatty
  • 17,190
  • 34
  • 81
  • 118
  • close the application by pressing home or back key?.. Coz if u close it by pressing hme then app will be in background and oncreate will not get fired – DeRagan Nov 03 '10 at 10:41
  • @Rahul, but why even turning on the wifi, it still gives no connection issue? – Adil Bhatty Nov 03 '10 at 10:43
  • I am not sure as where you are calling this line of code...If you are just checking for this condition under activities oncreate it will be called only once... – DeRagan Nov 03 '10 at 10:48
  • @kaibuki this may be issue of android device, same issue i am getting in my HTC Hero, even my wireless is on – Paresh Mayani Nov 03 '10 at 11:15
  • @Rahul I am calling this on each setOnClickListener() of button – Adil Bhatty Nov 03 '10 at 14:10
  • @Paresh I have samsung vibrant, but even on emulator also having same issue – Adil Bhatty Nov 03 '10 at 14:11
  • possible duplicate of [How to check internet access on Android? InetAddress never timeouts](http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts) – edorian Jan 10 '12 at 13:08
  • you don't have to test if the function returns certain value since the if evaluates this. You can write your conditionals like this: `if(CheckInternet.checkConn(introPage.this)) { ... } else { ... }` – dinigo Jan 03 '13 at 01:42

9 Answers9

69

Sometimes the active connection is not first in the list, or is inactive or in an error state. This is how I would do it:

  NetworkInfo i = conMgr.getActiveNetworkInfo();
  if (i == null)
    return false;
  if (!i.isConnected())
    return false;
  if (!i.isAvailable())
    return false;
  return true;

[EDIT 1] Don't forget to add this permission in the application manifest:

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Does this help you?

Emmanuel

Emmanuel
  • 16,791
  • 6
  • 48
  • 74
  • I was looking for checking internet connection on Android and found your answer. It looks simple and nice. But does it check 3G as well? Thx. – lomza Sep 21 '11 at 13:31
  • 2
    You have to check the type of network for this. i.getType() == ConnectivityManager.TYPE_MOBILE and you can even get the subtype. i.getSubType() == TelephonyManager.NETWORK_TYPE_* – Emmanuel Sep 21 '11 at 14:50
  • You could also use the ConnectivityManager ==> http://stackoverflow.com/a/4009133/186636 – Peter Ajtai Apr 13 '12 at 19:05
  • 1
    Please edit this to `return i != null && i.isConnected() && i.isAvailable();` – Mr_and_Mrs_D Sep 22 '13 at 17:50
  • @Mr_and_Mrs_D: See I copy/pasted some code I had where I applied the "Replace Nested Conditional with Guard Clauses" refactoring. These 3 conditions are just the beginning; there were other conditions also. That plus it's more readable. – Emmanuel Sep 23 '13 at 14:37
  • not more readable as you can see : http://stackoverflow.com/a/8343843/281545 - plus the more concise an answer the better ;) – Mr_and_Mrs_D Sep 23 '13 at 15:32
  • 2
    @Emmanuel : plus, in some countries there are laws against if blocks without {}. – njzk2 Dec 04 '13 at 21:28
  • can any one here help me to defining what is conMgr in this code. – Hitesh Matnani Oct 03 '14 at 08:52
  • @Hitesh Matnani, it's the class [ConnectivityManager](http://developer.android.com/reference/android/net/ConnectivityManager.html). For [example](http://www.programcreek.com/java-api-examples/index.php?api=android.net.ConnectivityManager). – Emmanuel Dec 02 '14 at 18:12
3

The short answer:

public boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager)getActivity().getApplicationContext()
                                              .getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;
}
Avinesh
  • 535
  • 4
  • 10
beerLantern
  • 482
  • 7
  • 23
2
public static boolean checkNetworkStatus(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    TelephonyManager telephony = (TelephonyManager) context
            .getSystemService(Context.TELEPHONY_SERVICE);
    NetworkStatus netStatus = new NetworkStatus(connectivity, telephony);
    if (netStatus.isNetworkAvailable() == true) {
        Log.e(" in checkNetworkStatus()", "network available");
        return true;
    } else {
        Log.e(" in checkNetworkStatus()", "no network");
        return false;
    }
}

wifi-


void chkStatus() {
    final ConnectivityManager connMgr = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final android.net.NetworkInfo wifi = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    final android.net.NetworkInfo mobile = connMgr
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (wifi.isAvailable()) {
        Toast.makeText(this, "Wifi", Toast.LENGTH_LONG).show();
    } else if (mobile.isAvailable()) {
        Toast.makeText(this, "Mobile 3G ", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(this, "No Network ", Toast.LENGTH_LONG).show();
    }
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
sravan
  • 5,303
  • 1
  • 31
  • 33
2

Is better:

if (conMgr != null) {
    NetworkInfo i = conMgr.getActiveNetworkInfo();
    if (i != null) {
        if (!i.isConnected())
            ret = false;
        if (!i.isAvailable())
            ret = false;                
    }

    if (i == null)
        ret = false;

} else
    ret = false;

with the other form, if "Network i" is equal null then, check after for !i.isConnected() must fail (i is null).

Justin
  • 84,773
  • 49
  • 224
  • 367
peludito
  • 21
  • 1
1

Try this:

public boolean isInternetAvailable(Context context) {
        ConnectivityManager conMgr = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
         NetworkInfo i = conMgr.getActiveNetworkInfo();
          if (i == null)
            return false;
          if (!i.isConnected())
            return false;
          if (!i.isAvailable())
            return false;
          return true;

    }

and this permission:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Milad Faridnia
  • 9,113
  • 13
  • 65
  • 78
0

Hi try the following code :

   public class NetworkCheckDemo extends Activity
 {
TextView tvstatus;
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tvstatus=(TextView)findViewById(R.id.txtviewstatus);
    ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo nf=cn.getActiveNetworkInfo();
    if(nf != null && nf.isConnected()==true )
    {
        Toast.makeText(this, "Network Available", Toast.LENGTH_LONG).show();
        tvstatus.setText("Network Available");
    }
    else
    {
        Toast.makeText(this, "Network Not Available", Toast.LENGTH_LONG).show();
        tvstatus.setText("Network Not Available");
      }
    }
  }

Add below 3 permissions in Android Manifest File.

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
androidgeek
  • 3,440
  • 1
  • 15
  • 27
0

I used to check if I have connectivity, don't forget to check if the NetworkInfo is null or not because on tablet where mobile data connectivity is not provided, the NetworkInfo for TYPE_MOBILE return null.

public static boolean collectionAllowed(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(
            ConnectivityManager.TYPE_MOBILE);
    State mobile = NetworkInfo.State.DISCONNECTED;
    if ( mobileInfo != null) {
        mobile = mobileInfo.getState();
    }
    NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(
            ConnectivityManager.TYPE_WIFI);
    State wifi = NetworkInfo.State.DISCONNECTED;
    if ( wifiInfo != null) {
        wifi = wifiInfo.getState();
    }
    boolean dataOnWifiOnly = (Boolean) PreferenceManager
            .getDefaultSharedPreferences(context).getBoolean(
                    "data_wifi_only", true);
    if ((!dataOnWifiOnly && (mobile.equals(NetworkInfo.State.CONNECTED) || wifi
            .equals(NetworkInfo.State.CONNECTED)))
            || (dataOnWifiOnly && wifi.equals(NetworkInfo.State.CONNECTED))) {
        return true;
    } else {
        return false;
    }
}
ITDoVe
  • 29
  • 9
0

same as the approved answer but in short :

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm = (ConnectivityManager)
            context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    return info != null && info.isConnected() && info.isAvailable();
}
Ahmed Adel Ismail
  • 2,168
  • 16
  • 23
0

You can use this awesome gist by emil2k :

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

public class Connectivity {
    public static NetworkInfo getNetworkInfo(Context context){
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo();
    }

    public static boolean isConnected(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected());
    }

    public static boolean isConnectedWifi(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
    }

    public static boolean isConnectedMobile(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
    }

    public static boolean isConnectedFast(Context context){
        NetworkInfo info = Connectivity.getNetworkInfo(context);
        return (info != null && info.isConnected() && Connectivity.isConnectionFast(info.getType(),info.getSubtype()));
    }

    public static boolean isConnectionFast(int type, int subType){
        if(type==ConnectivityManager.TYPE_WIFI){
            return true;
        }else if(type==ConnectivityManager.TYPE_MOBILE){
            switch(subType){
            case TelephonyManager.NETWORK_TYPE_1xRTT:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_CDMA:
                return false; // ~ 14-64 kbps
            case TelephonyManager.NETWORK_TYPE_EDGE:
                return false; // ~ 50-100 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_0:
                return true; // ~ 400-1000 kbps
            case TelephonyManager.NETWORK_TYPE_EVDO_A:
                return true; // ~ 600-1400 kbps
            case TelephonyManager.NETWORK_TYPE_GPRS:
                return false; // ~ 100 kbps
            case TelephonyManager.NETWORK_TYPE_HSDPA:
                return true; // ~ 2-14 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPA:
                return true; // ~ 700-1700 kbps
            case TelephonyManager.NETWORK_TYPE_HSUPA:
                return true; // ~ 1-23 Mbps
            case TelephonyManager.NETWORK_TYPE_UMTS:
                return true; // ~ 400-7000 kbps
            /*
             * Above API level 7, make sure to set android:targetSdkVersion 
             * to appropriate level to use these
             */
            case TelephonyManager.NETWORK_TYPE_EHRPD: // API level 11 
                return true; // ~ 1-2 Mbps
            case TelephonyManager.NETWORK_TYPE_EVDO_B: // API level 9
                return true; // ~ 5 Mbps
            case TelephonyManager.NETWORK_TYPE_HSPAP: // API level 13
                return true; // ~ 10-20 Mbps
            case TelephonyManager.NETWORK_TYPE_IDEN: // API level 8
                return false; // ~25 kbps 
            case TelephonyManager.NETWORK_TYPE_LTE: // API level 11
                return true; // ~ 10+ Mbps
            // Unknown
            case TelephonyManager.NETWORK_TYPE_UNKNOWN:
            default:
                return false;
            }
        }else{
            return false;
        }
    }

}
Rohit Arya
  • 6,751
  • 1
  • 26
  • 40