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.
– LevitDec 5 '14 at 9:29

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áriJun 5 '16 at 15:22

@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.
– LevitFeb 21 '17 at 11:02

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!
– BlejzerJan 20 '15 at 11:05

8

Keep in mind this approach is a blocking one so you shouldn't execute it in the UI therad
– SergiiMay 28 '15 at 10:20

33

@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.
– Roon13Jun 4 '15 at 3:37

9

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 YilmazJun 30 '15 at 14:40

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.

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.
– midnightAug 5 '12 at 20:06

20

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.
– miguelJan 31 '14 at 2:01

9

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 RaJFeb 15 '14 at 21:30

This one should be definitely under the correct answer (wasted too much time figuring out what the hell is wrong).
– Indrek KõueAug 17 '11 at 10:05

2

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.
– TomJan 14 '12 at 21:50

3

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 CastelijnsNov 25 '15 at 19:38

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.
– TomJan 14 '12 at 21:51

28

@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
– slinden77Jul 31 '12 at 11:56

2

@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.
– TomJul 31 '12 at 16:22

9

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.
– BenjaminAug 30 '13 at 18:34

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 VestnesOct 13 '09 at 16:07

1

There was a mistake in the EDIT EDIT section, I'd left out the requestRouteToHost() call. Re-read the answer now :)
– Chinmay KanchiOct 13 '09 at 16:11

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.

As seen in answers ConnectivityManager is a solution, I just added it within a method this is a simplified method all useConnectivityManager returns true if there is a network access not Internet access, means if your WiFi is connected to a router but the router has no internet it returns true, it check connection availability

you have to check Internet on AsyncTask, otherwise it can throw android.os.NetworkOnMainThreadException in some cases

ConnectivityManager used to check the network access if true sends request (Ping)

Request send to http://clients3.google.com/generate_204, This well-known URL is known to return an empty page with an HTTP status 204 this is faster and more efficient than http://www.google.com , read this. if you have website it's preferred to put you website instead of google, only if you use it within the app

Timeout can be changed range (20ms -> 2000ms), 1500ms is commonly used

Great question, its sad you dont have more points. This must be the correct answer.
– Jhon Fredy Trujillo OrtegaFeb 27 '18 at 15:23

I am new to android. though, This is well covered answer and it get more attention @7569106
– Mazen EmbabyMay 10 '18 at 14:15

1

best and complete answer, thank you. if someone have a website notice that condition must like this urlc.getResponseCode() == 200 and not need to check urlc.getContentLength() == 0
– AREFSep 13 '18 at 9:59

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.

+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.
– GreyBeardedGeekJul 1 '13 at 20:40

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:

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_pollachiJun 19 '13 at 14:57

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)
– 正宗白布鞋Jun 19 '13 at 15:06

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).
– YashJul 26 '13 at 22:12

2

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.
– YashJul 26 '13 at 22:44

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 PombeiroFeb 8 '14 at 0:11

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.

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.
– TiagoSep 20 '15 at 22:24

2

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 LlausasSep 21 '15 at 19:14

Nice summary of the device connectivity components, just need to wrap them in try/catch statements to avoid crashes. Similarly, just make your routine HttpURLConnection calls, as long as they're wrapped in error handling, you'll soon know whether or not you have an internet connection
– rangiMar 28 at 18:45

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:

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

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).