How to check internet access on Android? InetAddress never times out

I got a AsyncTask that is supposed to check the network access to a host name. But the doInBackground() is never timed out. Anyone have a clue?

public class HostAvailabilityTask extends AsyncTask<String, Void, Boolean> {

    private Main main;

    public HostAvailabilityTask(Main main) {
        this.main = main;
    }

    protected Boolean doInBackground(String... params) {
        Main.Log("doInBackground() isHostAvailable():"+params[0]);

        try {
            return InetAddress.getByName(params[0]).isReachable(30); 
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;       
    }

    protected void onPostExecute(Boolean... result) {
        Main.Log("onPostExecute()");

        if(result[0] == false) {
            main.setContentView(R.layout.splash);
            return;
        }

        main.continueAfterHostCheck();
    }   
}
13.10.2009 14:59:51
To check for an internet connection, probably the most reliable way would be to ping one of the major name servers, this could be done for example with if(Runtime.getRuntime().exec("/system/bin/ping -c 1 8.8.8.8").waitFor()==0) .... See my answer for a nicer implementation of this. Btw the accepted answer (and many others here) just check for a network connection, not the internet.
Levite 5.12.2014 09:29:19
CrandellWS 30.01.2016 19:10:59
Do not use the ping method, use a HTTP check instead. ICMP is blocked on some networks, so ping will not work. E.g.: it works perfectly on my home wifi, but it does not when I am using mobile data on Vodafone's network (in Hungary). Or combine the 2 methods as a fallback, but be careful because waitFor() will wait about 20 seconds even if -w or -W is used.
Tamás Bolvári 5.06.2016 15:22:42
0xAliHn 29.09.2016 09:28:47
@TamásBolvári: Even better would be to tackle it at the tcp layer. Which should get you close to the speed of an ICMP, with the reliabilty of an HTTP request. I edited the "ping answer" accordingly.
Levite 21.02.2017 11:02:22
30 ОТВЕТОВ
РЕШЕНИЕ

Network connection / Internet access

  • isConnectedOrConnecting() (used in most answers) checks for any network connection
  • To know whether any of those networks have internet access, use one of the following

A) Ping a Server (easy)

// ICMP 
public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    }
    catch (IOException e)          { e.printStackTrace(); }
    catch (InterruptedException e) { e.printStackTrace(); }

    return false;
}

+ could run on main thread

- does not work on some old devices (Galays S3, etc.), it blocks a while if no internet is available.

B) Connect to a Socket on the Internet (advanced)

// TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.)
public boolean isOnline() {
    try {
        int timeoutMs = 1500;
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

        sock.connect(sockaddr, timeoutMs);
        sock.close();

        return true;
    } catch (IOException e) { return false; }
}

+ very fast (either way), works on all devices, very reliable

- can't run on the UI thread

This works very reliably, on every device, and is very fast. It needs to run in a separate task though (e.g. ScheduledExecutorService or AsyncTask).

Possible Questions

  • Is it really fast enough?

    Yes, very fast ;-)

  • Is there no reliable way to check internet, other than testing something on the internet?

    Not as far as I know, but let me know, and I will edit my answer.

  • What if the DNS is down?

    Google DNS (e.g. 8.8.8.8) is the largest public DNS in the world. As of 2013 it served 130 billion requests a day. Let 's just say, your app would probably not be the talk of the day.

  • Which permissions are required?

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

    Just internet access - surprise ^^ (Btw have you ever thought about, how some of the methods suggested here could even have a remote glue about internet access, without this permission?)

 

Extra: One-shot AsyncTask Example

class InternetCheck extends AsyncTask<Void,Void,Boolean> {

    private Consumer mConsumer;
    public  interface Consumer { void accept(Boolean internet); }

    public  InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); }

    @Override protected Boolean doInBackground(Void... voids) { try {
        Socket sock = new Socket();
        sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
        sock.close();
        return true;
    } catch (IOException e) { return false; } }

    @Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); }
}

///////////////////////////////////////////////////////////////////////////////////
// Usage

    new InternetCheck(internet -> { /* do something with boolean response */ });

Extra: One-shot RxJava/RxAndroid Example (Kotlin)

fun hasInternetConnection(): Single<Boolean> {
  return Single.fromCallable {
    try {
      // Connect to Google DNS to check for connection
      val timeoutMs = 1500
      val socket = Socket()
      val socketAddress = InetSocketAddress("8.8.8.8", 53)

      socket.connect(socketAddress, timeoutMs)
      socket.close()

      true
    } catch (e: IOException) {
      false
    }
  }
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
}

///////////////////////////////////////////////////////////////////////////////////
    // Usage

    hasInternetConnection().subscribe { hasInternet -> /* do something */}
544
20.06.2018 09:48:28
This is great peace of code! I found it very useful on devices that use prepaid cards! When they run out of money, they have internet access available, but no internet. So just checking for connectivity would not do. THANK YOU!
Blejzer 20.01.2015 11:05:08
Keep in mind this approach is a blocking one so you shouldn't execute it in the UI therad
Sergii 28.05.2015 10:20:56
@Levit This should be the accepted answer. Above answer just checks Network n NOT INTERNET CONNECTION. And yes this is very fast. Thanks. Hence upvote.
Roon13 4.06.2015 03:37:00
This solution is not working for all devices. Some devices are always returning 2 as @Salmaan stated. The devices I tested had internet connection and the ping target is the Google DNS server - which is responding to ping requests. I think some vendors are not permitting ping requests. For example, I tested with a Samsung 10.1 tablet (4.3), and the solution is not working. When I run the ping command through the command line utility, I get a permission error. The command is also not working on emulators. Be careful using this solution.
Eren Yilmaz 30.06.2015 14:40:33
This approach does not work on all phones. It fails for example on Samsung Galaxy S3. See here: Why does ping works on some devices and not others?
Adil Hussain 24.09.2015 18:53:10

Take a look at the ConnectivityManager class. You can use this class to get information on the active connections on a host. http://developer.android.com/reference/android/net/ConnectivityManager.html

EDIT: You can use

Context.getSystemService(Context.CONNECTIVITY_SERVICE)
    .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) 

or

Context.getSystemService(Context.CONNECTIVITY_SERVICE)
    .getNetworkInfo(ConnectivityManager.TYPE_WIFI) 

and parse the DetailedState enum of the returned NetworkInfo object

EDIT EDIT: To find out whether you can access a host, you can use

Context.getSystemService(Context.CONNECTIVITY_SERVICE)
    .requestRouteToHost(TYPE_WIFI, int hostAddress)

Obviously, I'm using Context.getSystemService(Context.CONNECTIVITY_SERVICE) as a proxy to say

ConnectivityManager cm = Context.getSystemService(Context.CONNECTIVITY_SERVICE);
cm.yourMethodCallHere();
46
2.11.2012 13:46:54
Not sure, but this seems like code to test what kind of network connection im currently on. E.g im on WiFi, there is no guarantee that you home wifi router is connected to internett... to check that you actually need to do a request to a internetserver...
Vidar Vestnes 13.10.2009 16:07:51
There was a mistake in the EDIT EDIT section, I'd left out the requestRouteToHost() call. Re-read the answer now :)
Chinmay Kanchi 13.10.2009 16:11:42
requestRouteToHost has been deprecated.
Jahaziel 7.07.2016 16:03:02

Im using this code instead of the InetAddress :

    try {

        URL url = new URL("http://"+params[0]);

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application:"+Z.APP_VERSION);
        urlc.setRequestProperty("Connection", "close");
        urlc.setConnectTimeout(1000 * 30); // mTimeout is in seconds
        urlc.connect();
        if (urlc.getResponseCode() == 200) {
            Main.Log("getResponseCode == 200");
            return new Boolean(true);
        }
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
5
13.10.2009 16:08:46
It would be great if you had clarified if the IOException means no internet connection and how reliable it could be.
Milad.Nozari 10.06.2015 14:27:42

No need to be complex. The simplest and framework manner is to use ACCESS_NETWORK_STATE permission and just make a connected method

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    return cm.getActiveNetworkInfo() != null && 
       cm.getActiveNetworkInfo().isConnectedOrConnecting();
}

You can also use requestRouteToHost if you have a particualr host and connection type (wifi/mobile) in mind.

You will also need:

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

in your android manifest.

296
26.05.2012 16:38:55
it is better to do a null check at cm.getActiveNetworkInfo() level it threw a null if no active network was available.
Samuel 8.03.2011 09:44:45
see stackoverflow.com/a/11691676/1979773 for a deeper exaplanation about requestRouteToHost()
Spartako 9.12.2013 10:02:16
I had to add the Context, in context.getSystemService or it doesn't work. I got my clue here androidhive.info/2012/07/…
Francisco Corrales Morales 4.06.2014 15:59:58
This solution will return true if you are connected to a WiFi hotspot, even if this hotspot does NOT have internet connectivity.
Josh 18.09.2015 07:33:05
Nilesh Rathod 27.09.2019 08:35:14

To get getActiveNetworkInfo() to work you need to add the following to the manifest.

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
63
26.05.2012 16:41:40
This one should be definitely under the correct answer (wasted too much time figuring out what the hell is wrong).
Indrek Kõue 17.08.2011 10:05:15
The INTERNET permission is NOT needed for this, just ACCESS_NETWORK_STATE. INTERNET is only needed if you are actually making connections to remote locations, not querying the state of the device's radio.
Tom 14.01.2012 21:50:11
Your answer is currently not really an answer, it's just a relatively minor addition to other answers. If all the other answers were not here, would your answer make sense? Not really. Because if that it is better to expand your answer with code on how to use it, or remove your answer and add the info in another answer (you will not lose any reputation)
Tim 25.11.2015 19:38:50
Be careful getActiveNetworkInfo() is deprecated in API level 29.
Stack Overflow 23.07.2019 19:47:18

If the device is in airplane mode (or presumably in other situations where there's no available network), cm.getActiveNetworkInfo() will be null, so you need to add a null check.

Modified (Eddie's solution) below:

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

Also add the following permission to the AndroidManifest.xml:

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

One other small point, if you absolutely need a network connection at the given point in time, then it might be better to use netInfo.isConnected() rather than netInfo.isConnectedOrConnecting. I guess this is up to the individual use-case however.

1032
1.09.2018 23:49:44
imo you still should and need to check for http timeout exceptions since there might be situations when a network is connected but there would no actual internet connection because the only way to access it is through, for instance, VPN - this way u have, for instance, WI-FI connection but no actual internet traffic. Another situation is a server hang-on. These are 2 issues that I've run recently and connection manager isn't gonna help there.
midnight 5.08.2012 20:06:48
I agree with midnight and Pintu, this answer should not be the accepted answer, it has nothing to do with checking wether you're on the internet. For example, if the phone is connected to a WiFi network with a captive portal, like at a hotel, this function will incorrectly return true. The correct answer is to ping a server on the public internet.
miguel 31.01.2014 02:01:36
when there is no working internet for my router, if I connect to router through wifi, then the above code is returning true. But, It is not supposed to be, right? Can you help me
MoHaN K RaJ 15.02.2014 21:30:23
I had to add the Context, in context.getSystemService or it doesn't work. I got my clue here androidhive.info/2012/07/…
Francisco Corrales Morales 4.06.2014 15:53:11
Nice way to check network availability. But how to check internet access?
Tamás Bolvári 4.06.2016 22:40:41

Found at and modified (!) from this link :

In your manifest file add at least:

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

You probably already have the INTERNET permission if you are accessing it. Then a boolean function that allows to test for connectivity is:

private boolean checkInternetConnection() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    // test for connection
    if (cm.getActiveNetworkInfo() != null
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    } else {
        Log.v(TAG, "Internet Connection Not Present");
        return false;
    }
}
26
10.02.2011 17:25:05

check this code... it worked for me :)

public static void isNetworkAvailable(final Handler handler, final int timeout) {
    // ask fo message '0' (not connected) or '1' (connected) on 'handler'
    // the answer must be send before before within the 'timeout' (in milliseconds)

    new Thread() {
        private boolean responded = false;   
        @Override
        public void run() { 
            // set 'responded' to TRUE if is able to connect with google mobile (responds fast) 
            new Thread() {      
                @Override
                public void run() {
                    HttpGet requestForTest = new HttpGet("http://m.google.com");
                    try {
                        new DefaultHttpClient().execute(requestForTest); // can last...
                        responded = true;
                    } 
                    catch (Exception e) {
                    }
                } 
            }.start();

            try {
                int waited = 0;
                while(!responded && (waited < timeout)) {
                    sleep(100);
                    if(!responded ) { 
                        waited += 100;
                    }
                }
            } 
            catch(InterruptedException e) {} // do nothing 
            finally { 
                if (!responded) { handler.sendEmptyMessage(0); } 
                else { handler.sendEmptyMessage(1); }
            }
        }
    }.start();
}

Then, I define the handler:

Handler h = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        if (msg.what != 1) { // code if not connected

        } else { // code if connected

        }   
    }
};

...and launch the test:

isNetworkAvailable(h,2000); // get the answser within 2000 ms
46
29.01.2014 10:46:53
What is Google is down? That also requires the INTERNET permission, which is unnecessary for the given task. Finally, that consumes data (even if insignificant). This just seems like such a kludge.
Tom 14.01.2012 21:51:32
@Tom to be fair, this is probably the only correct answer. The other examples merely show if a network connection is available and / or if there's a connection to that network, but don't answer the question if that network can actually also make a remote connection (for example to a website). So this answers the posters Q, and the other answers don't
slinden77 31.07.2012 11:56:00
@dmmh Yeah, that's unfortunately true from what I've seen with the Android APIs. Perhaps a simple ping might be better, stackoverflow.com/questions/3905358/…. If you were really concerned you could even include a list of IPs to ping, because while there is a very small chance Google will ever go down, there is an even smaller chance that Google, Bing, AND Yahoo will be down on the same day. Just my thoughts.
Tom 31.07.2012 16:22:13
There is no point in doing this check. If you are going to spend the system time and network resources to connect to Google, you could have spent them instead connecting to the resource you actually care about.
Benjamin 30.08.2013 18:34:22
In China Google was blocked!!
Anthone 9.10.2014 08:56:24
public boolean isOnline() {
    boolean var = false;
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if ( cm.getActiveNetworkInfo() != null ) {
        var = true;
    }
    return var;
} 

I have done it this way. A little bit shorter and more readable I guess.

Cheers!

Saiyan

2
19.11.2011 03:05:29
How come you don't call .isConnectedOrConnecting() ?
Carlos P 11.01.2012 12:43:46
I just didn´t do it :) I just check if the ConectivityManager has some network info. If it doesn´t, its because it is not connected.
InsaurraldeAP 9.02.2012 01:46:39
As all the other which didn't read the problem through, this does not solve the problem, since it does not really check for a connection to the internet. A connection to a local wifi hotspot will return true, even if the hotspot will not allow you to go through to the internet.
Pedro Pombeiro 8.02.2014 00:10:55

You can iterate over all network connections and chek whether there is at least one available connection:

public boolean isConnected() {
    boolean connected = false;

    ConnectivityManager cm = 
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

    if (cm != null) {
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();

        for (NetworkInfo ni : netInfo) {
            if ((ni.getTypeName().equalsIgnoreCase("WIFI")
                    || ni.getTypeName().equalsIgnoreCase("MOBILE"))
                    && ni.isConnected() && ni.isAvailable()) {
                connected = true;
            }

        }
    }

    return connected;
}
6
13.02.2012 07:34:01

It is not complex to check Android network / internet connectivity status. The below DetectConnection class will help you to check this status:

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

public class DetectConnection {
    public static boolean checkInternetConnection(Context context) {
        ConnectivityManager con_manager = (ConnectivityManager) context
                                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if (con_manager.getActiveNetworkInfo() != null
            && con_manager.getActiveNetworkInfo().isAvailable()
            && con_manager.getActiveNetworkInfo().isConnected()) {
                return true;
        } else {
            return false;
        }
    }
}

For more details visit How to Check Android Network / Internet Connectivity Status

5
18.07.2012 22:17:54

I made this code, it is the simplest and it is just a boolean. by asking if(isOnline()){

You get if there is a connection and if it can connect to a page the status code 200 (stable connection).

Make sure to add the correct INTERNET and ACCESS_NETWORK_STATE permissions.

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://www.google.com");
            HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setConnectTimeout(3000);
            urlc.connect();
            if (urlc.getResponseCode() == 200) {
                return new Boolean(true);
            }
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return false;
}
18
11.04.2013 09:37:41
Maybe you should replace 200 by HttpURLConnection.HTTP_OK
Yash 26.07.2013 22:55:29
What if Google is down?
Yauraw Gadav 26.03.2015 14:26:08

It's works for me. Try it out.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    try {
        URL url = new URL("http://stackoverflow.com/posts/11642475/edit" );
        //URL url = new URL("http://www.nofoundwebsite.com/" );
        executeReq(url);
        Toast.makeText(getApplicationContext(), "Webpage is available!", Toast.LENGTH_SHORT).show();
    }
    catch(Exception e) {
        Toast.makeText(getApplicationContext(), "oops! webpage is not available!", Toast.LENGTH_SHORT).show();
    }
}

private void executeReq(URL urlObject) throws IOException
{
    HttpURLConnection conn = null;
    conn = (HttpURLConnection) urlObject.openConnection();
    conn.setReadTimeout(30000);//milliseconds
    conn.setConnectTimeout(3500);//milliseconds
    conn.setRequestMethod("GET");
    conn.setDoInput(true);

    // Start connect
    conn.connect();
    InputStream response =conn.getInputStream();
    Log.d("Response:", response.toString());
}}
6
19.06.2013 14:46:47
This answer can not work now, since we can not access network on main thread now.
正宗白布鞋 19.06.2013 14:44:44
I mean from API level 11, this doesn't work. Reason: developer.android.com/reference/android/os/…. If it works for you, it means you're running this code on old android device. (prior to GB).
正宗白布鞋 19.06.2013 14:53:58
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); add these two lines two your program for avoiding network main thread exception
selva_pollachi 19.06.2013 14:57:17
Ok, I should not say this cannot work, I should say it can work (by target old version or Strictmode setup) but is discouraged. This may cause ANR easily. (With so high timeout configuration in httpurlconnection)
正宗白布鞋 19.06.2013 15:06:19
ya..you are right.. just i put this because this is also one of the way.
selva_pollachi 19.06.2013 17:13:47

Of everything I have seen so far shortest and cleanest way should be:

public final static boolean isConnected( Context context )
{   
   final ConnectivityManager connectivityManager = 
         (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );  
   final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();    
   return networkInfo != null && networkInfo.isConnected();
}

PS: This does not ping any host, it just checks the connectionstatus, so if your router has no internet connection and your device is connected to it this method would return true although you have no internet.
For an actual test I would recommend execuding a HttpHead request (e.g. to www.google.com) and check the status, if its 200 OK everything is fine and your device has an internet connection.

8
19.09.2012 08:19:08
I wanted to put this method in a global class so I had to use this version so I could pass the Context from the Activity I was calling it from. Thanks!
RyanG 25.10.2012 14:40:33

For me it was not a good practice to check the connection state in the Activity class, because

ConnectivityManager cm =
    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

should be called there, or you need to push down your Activity instance (context) to the connection handler class to able to check the connection state there When no available connection (wifi, network) I catch the UnknownHostException exception:

JSONObject jObj = null;
Boolean responded = false;
HttpGet requestForTest = new HttpGet("http://myserver.com");
try {
    new DefaultHttpClient().execute(requestForTest);
    responded = true;
} catch (UnknownHostException e) {
    jObj = new JSONObject();
    try {
        jObj.put("answer_code", 1);
        jObj.put("answer_text", "No available connection");
    } catch (Exception e1) {}
    return jObj;
} catch (IOException e) {
    e.printStackTrace();
}

In this way I can handle this case along with the other cases in the same class (my server always response back with a json string)

6
25.11.2012 12:39:22

Best approach:

public static boolean isOnline() {
    try {
    InetAddress.getByName("google.com").isReachable(3);

    return true;
    } catch (UnknownHostException e){
    return false;
    } catch (IOException e){
    return false;
    }
    }
5
27.01.2013 11:12:36
I like this approach but I have to point out some things. isReachable() returns a boolean, therefore instead of returning true in the try section, you could do it like boolean connected = InetAddress.getByName("google.com").isReachable(3); then return connected. Also, isReacheable throws IOException and IllegalArgumentException exceptions, therefore itll be a good idea of replacing UnknownHostException with IllegalArgumentException and including a third catch: catch (Exception E).
Yash 26.07.2013 22:12:01
But then, isReachable uses ICMP which might require root privileges and uses port 7 which usually has no running services on the latest systems. Therefore the best way to check the route to an online service is by regular TCP; hence a down vote.
Yash 26.07.2013 22:44:31

Following is the code from my Utils class:

public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
5
11.06.2013 09:22:36

One important use case on mobile devices to it ensure an actual connection exists. This is a common problem when a mobile user enters a Wifi network with a "Captive Portal", in which they need to sign in. I use this blocking function in the background to ensure a connection exists.

/*
 * Not Thread safe. Blocking thread. Returns true if it
 * can connect to URL, false and exception is logged.
 */
public boolean checkConnectionHttps(String url){
    boolean responded = false;
    HttpGet requestTest = new HttpGet(url);
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, 3000);
    HttpConnectionParams.setSoTimeout(params, 5000);
    DefaultHttpClient client = new DefaultHttpClient(params);
    try {
        client.execute(requestTest);
        responded = true;
    } catch (ClientProtocolException e) {
        Log.w(MainActivity.TAG,"Unable to connect to " + url + " " + e.toString());
    } catch (IOException e) {
        Log.w(MainActivity.TAG,"Unable to connect to " + url + " " + e.toString());
        e.printStackTrace();
    }
    return responded;
}
7
13.06.2013 16:36:54
+1 for actually checking end-to-end connectivity. For the "Captive Portal" situation, however, I've found that many will pass the above test even if you haven't signed in - you get the login page and a 200 response no matter what url you ask for. So I attempt to hit a page on my own domain that I know does not exist, and make sure that I get a 404. Alternately, you could hit a known existing page, make sure that you get a 200, and check the content that is returned to make sure that it's what you expect.
GreyBeardedGeek 1.07.2013 20:40:04

Here is the method I use:

public boolean isNetworkAvailable(final Context context) {
    return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}

Even better, check to make sure it is "connected":

public boolean isNetworkAvailable(final Context context) {
    final ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
    return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}

Here is how to use the method:

if (isNetworkAvailable(context)) {
    // code here
} else {
    // code
}

Permission needed:

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

https://stackoverflow.com/a/16124915/950427

8
23.05.2017 11:54:59
public static boolean isNetworkAvailable(Context ctx) {
ConnectivityManager connMgr = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected() ||
    connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()){
        return true;
}

return false;
 } 

user this

2
3.10.2013 10:22:57
public class Network {

Context context;

public Network(Context context){
    this.context = context;
}

public boolean isOnline() {
    ConnectivityManager cm =
            (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null &&
                          activeNetwork.isConnectedOrConnecting();
}

}
5
24.10.2013 15:51:04
As all the other which didn't read the problem through, this does not solve the problem, since it does not really check for a connection to the internet. A connection to a local wifi hotspot will return true, even if the hotspot will not allow you to go through to the internet.
Pedro Pombeiro 8.02.2014 00:11:14

Update 29/06/2015 If you are using Xamarin.Android and want to check for connectivity, you can use a Nuget package that would give you this functionality on multiple platforms. Good candidates are here and here. [End of Update]

The Answers above are quite good, but they are all in Java, and almost all of them check for a connectivity. In my case, I needed to have connectivity with a specific type of connection and I am developing on Xamarin.Android. Moreover, I do not pass a reference to my activities Context in the Hardware layer, I use the Application Context. So here is my solution, in case somebody comes here with similar requirements. I have not done full testing though, will update the answer once I am done with my testing

using Android.App;
using Android.Content;
using Android.Net;

namespace Leopard.Mobile.Hal.Android
{
    public class AndroidNetworkHelper
    {
        public static AndroidNetworkStatus GetWifiConnectivityStatus()
        {
            return GetConnectivityStatus(ConnectivityType.Wifi);
        }

        public static AndroidNetworkStatus GetMobileConnectivityStatus()
        {
            return GetConnectivityStatus(ConnectivityType.Mobile);
        }

        #region Implementation

        private static AndroidNetworkStatus GetConnectivityStatus(ConnectivityType connectivityType)
        {
            var connectivityManager = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService);
            var wifiNetworkInfo = connectivityManager.GetNetworkInfo(connectivityType);
            var result = GetNetworkStatus(wifiNetworkInfo);
            return result;
        }

        private static AndroidNetworkStatus GetNetworkStatus(NetworkInfo wifiNetworkInfo)
        {
            var result = AndroidNetworkStatus.Unknown;
            if (wifiNetworkInfo != null)
            {
                if (wifiNetworkInfo.IsAvailable && wifiNetworkInfo.IsConnected)
                {
                    result = AndroidNetworkStatus.Connected;
                }
                else
                {
                    result = AndroidNetworkStatus.Disconnected;
                }
            }
            return result;
        } 

        #endregion
    }

    public enum AndroidNetworkStatus
    {
        Connected,
        Disconnected,
        Unknown
    }
3
29.06.2015 11:25:17

The other answers that use ConnectivityManager are wrong because having a network connection doesn't mean you have internet access. For example, the user might be connected to a coffee shop's WiFi portal but can't get to the internet. To check that the internet is accessible you have to try to connect to an actual server. Normally when you want to do this you have a specific server in mind that you want to connect to, so go ahead and check if you can connect to that server. Here's a simple method for checking connectivity to a server.

private boolean isOnTheInternet() {
    try {
        URLConnection urlConnection = new URL("http://yourserver").openConnection();
        urlConnection.setConnectTimeout(400);
        urlConnection.connect();
        return true;
    } catch (Exception e) {
        return false;
    }
}

The reason for setting the ConnectTimeout is that otherwise it defaults to the TCP timeout which can be many seconds long.

Note also that Android won't let you run this on your main thread.

3
29.06.2015 18:26:51

This method gives you the option for a really fast method (for real time feedback) or a slower method (for one off checks that require reliability)

public boolean isNetworkAvailable(bool SlowButMoreReliable) {
    bool Result = false; 
    try {
        if(SlowButMoreReliable){
            ConnectivityManager MyConnectivityManager = null;
            MyConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo MyNetworkInfo = null;
            MyNetworkInfo = MyConnectivityManager.getActiveNetworkInfo();

            Result = MyNetworkInfo != null && MyNetworkInfo.isConnected();

        } else
        {
            Runtime runtime = Runtime.getRuntime();
            Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");

            int i = ipProcess.waitFor();

            Result = i== 0;

        }

    } catch(Exception ex)
    {
        //Common.Exception(ex); //This method is one you should have that displays exceptions in your log
    }
    return Result;
}
6
13.08.2015 09:13:54

It does works for me:

To verify network availability:

private Boolean isNetworkAvailable() {
ConnectivityManager connectivityManager 
      = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();}

To verify internet access:

public Boolean isOnline() {
    try {
        Process p1 = java.lang.Runtime.getRuntime().exec("ping -c 1 www.google.com");
        int returnVal = p1.waitFor();
        boolean reachable = (returnVal==0);
        return reachable;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}
12
7.03.2014 17:39:27
this is a great solution to check if a server si up, works really fine. thanks!
Williew 5.10.2014 20:50:58
the isOnline() shouldn't run on main thread at all, as if there is wi-fi signal but no internet it will take too long and block the main thread.
humazed 16.09.2015 04:18:00

Its so great to have more then one way to code. Here is my example.

ConnectivityManager icheck = getSystemService(Context.CONNECTIVITY_SERVICE);

TextView tv = findViewById(R.id.textView1);

boolean wifi = icheck.getActiveNetworkInfo() != null;
        if(wifi) {
        tv.setText("Internet is on.");  
        } else {
             tv.setText("Internet is off.");    
        }

Good luck.

2
30.06.2014 11:23:22

Just create the following class which checks for an internet connection:

public class ConnectionStatus {

    private Context _context;

    public ConnectionStatus(Context context) {
        this._context = context;
    }

    public boolean isConnectionAvailable() {
        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;
    }
}

This class simply contains a method which returns the boolean value of the connection status. Therefore in simple terms, if the method finds a valid connection to the Internet, the return value is true, otherwise false if no valid connection is found.

The following method in the MainActivity then calls the result from the method previously described, and prompts the user to act accordingly:

public void addListenerOnWifiButton() {
        Button btnWifi = (Button)findViewById(R.id.btnWifi);

        iia = new ConnectionStatus(getApplicationContext());

        isConnected = iia.isConnectionAvailable();
        if (!isConnected) {
            btnWifi.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    Toast.makeText(getBaseContext(), "Please connect to a hotspot",
                            Toast.LENGTH_SHORT).show();
                }
            });
        }
        else {
            btnWifi.setVisibility(4);
            warning.setText("This app may use your mobile data to update events and get their details.");
        }
    }

In the above code, if the result is false, (therefore there is no internet connection, the user is taken to the Android wi-fi panel, where he is prompted to connect to a wi-fi hotspot.

3
4.09.2014 11:51:11

You can use this method to detect network availability-

public static boolean isDeviceOnline(Context context) {
        boolean isConnectionAvail = false;
        try {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            return netInfo.isConnected();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isConnectionAvail;
    }
5
4.02.2015 08:21:31
4
18.10.2015 14:11:15
But the method described there does not really check for Internet connection, it just checks if a connection is established (whether is has access to the Internet or not). The title of that official doc is really misleading.
Tiago 20.09.2015 22:24:54
Giving an answer to the question is better than just posting a link to information. What if the link goes dead? We will have no answer.
Jose Llausas 21.09.2015 19:14:49
if(isConnected()){
                Toast.makeText(getApplication(),"Thank you",Toast.LENGTH_SHORT).show();
        }
        else{

            AlertDialog.Builder builder =
                    new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
            builder.setTitle("Amar Bhat");
            builder.setMessage("Oops...You are not connected to Internet!!!");
            builder.setPositiveButton("OK", null);
            builder.setNegativeButton("Cancel", null);
            builder.show();
            //Toast.makeText(getApplication(),"You are not connected",Toast.LENGTH_SHORT).show();
        }




//And outside the class define isConnected()

 public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }

// In minifest add these permission
<uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
0
17.11.2015 05:25:36