0

There is a problem, I want to monitor internet connection.

There is good way with BradcastReceiver witch handles android.net.conn.CONNECTIVITY_CHANGE action. But this is not enough.

I want to know when internet is reachable. For example: If I disconnect wan wire from the router, I want that my app notice it and tell me that I am "Offline" despite wifi is connected.

So, is there some default android solution, or should I make thread witch repeatedly ping to some host? Or maybe something else?

Thanks

MartasSan
  • 135
  • 1
  • 7

2 Answers2

0

You simply can't do what you want. Connectivity could be broken anywhere on the Internet for some reason - you have no way to know this.

If you need to know whether you can reach a particular address then the only reliable way is to use a heartbeat signal - a Ping, or regular traffic on a persistent connection.

  • Not fully the truth: see http://stackoverflow.com/questions/6493517/android-detect-if-device-has-internet-connection; though this might still not guarantee access to desired end points ... :) – Trinimon Oct 08 '13 at 19:54
  • Why that right answer is better than ping to same address? – MartasSan Oct 08 '13 at 20:17
  • @Trinimon The answers to your suggested question say pretty much what I said here. –  Oct 08 '13 at 21:10
  • @MartasSan Not all servers will respond to a ping, although they'll respond to a proper connection. HTTP is probably the most commonplace, but it's a bit heavyweight as it uses TCP - hence the suggestion for a persistent connection. Sending a UDP packet will be lighter if you have a responder available on the target machine. –  Oct 08 '13 at 21:13
  • @Mike W: my comment was related to "You simply can't do what you want." - the part which is not true ;) ... the linked answer gives some code nice in addition. – Trinimon Oct 09 '13 at 06:36
0

As far as I know there's no simple way to test if the Internet is reachable. You could repeatedly ping to some host but this is not a good practice. It's very battery inefficient approach. When your app makes a request and fails then you should consider that Internet is not reachable and show appropriate toast message, screen or whatever. Also I suggest you to look at some well written apps like Google Play Store and I see how they solve such problems. At least this is what I do :)

Egis
  • 4,048
  • 4
  • 34
  • 50