Android - How do I detect that my app has lost internet connection although i'm still connected to WiFi

StackOverflow https://stackoverflow.com/questions/23500493

  •  16-07-2023
  •  | 
  •  

Question

I have an Application that has one feature that tells users when they are online/offline. But there is a case that fails completely.

I've searched all the web (searched correctly I hope) for a solution for my problem, but never really found one. The use case is the following:

Pre-conditions:

  • Android device
  • Wi-Fi

Description of the problem:

1 - I'm connected to a wireless router
2 - The router is connected to the internet
3 - For some reason the router looses connection to the internet (I'm still connected to the router but it doesn't have connection to the Internet)

Problem:

  • I've tried to use a Broadcast Receiver with different types of actions, but they are all triggered ONLY when WiFi connection is lost/connected... NOT when WiFi does not offer web access.

What I need:

  • I need to catch (if possible) an event that tells me "Hey, your internet status have changed", so that I can check if I can access.
Was it helpful?

Solution

I think what you want/need to do is to create a background service, configured to run periodically using the AlarmManager, that will check whether a reliable network resource is available (i.e. ping a server that you trust to be online all the time).

If your ping action succeeds than you are online and connected to the internet; if it fails then you're connected but not online.

There is a compromise you will have to make between accuracy (frequency of checks) and performance with respect to battery life because waking up the service and making a web request will not be easy on the battery if you do it all the time.

OTHER TIPS

Very few systems can actually do this. I'm not entirely sure that it exists, open source anyways. Think about major consumer electronics, do errors like this ever actually come up? Even with the situation being the same?

Most likely, you'd need to have a constant checking of a working internet connection. Be via the background loading of a webpage, sending data/pinging to server, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top