0

I've been needing a way to check if the user has Internet. I used this approach:

public 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();
            Log.w("INTERNET CHECK", "has Internet");
            return true;
        } catch (IOException e) {
            Log.w("INTERNET CHECK", "NO Internet");
            return false;
        }

    }

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

... the following way:

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

However, it seems like it isn't as robust as one would think: sometimes (not so often) my phone is connected to WiFi and yet this method returns false.

What are the possible scenarios/diagnostics as of why this behaviour might happen?

My personal experience is that it seems to happen when my phone has my application open and is connected to a WiFi. Then, the phone goes to sleep and I move places and open it back up to the application on a new WiFi connection. The check returns false despite my phone displaying that it clearly has established the new WiFi connection (since it was a saved network).

However, this is not the only way this method seems to have failed. Another developer had it happen while he didn't change his WiFi connection.

payne
  • 4,691
  • 8
  • 37
  • 85

1 Answers1

3

Wifi connections are disconnected when the phone goes to sleep. It takes time for the connection to be re-established when the phone wakes up again.

Your 1.5 second connection timeout is too short to accommodate that extra delay.

Also, the DNS server, or the intermediate network, may simply be busy. Again, the connection timeout is too short.


Before inventing your own way to check internet connectivity, you should read these:

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • Sounds like it's a reasonable explanation. What would be a recommendable timeout value? – payne Sep 09 '18 at 17:40
  • @payne That's for you to decide the optimal value, balancing false negatives vs excessive wait times for a true negative. – Andreas Sep 09 '18 at 17:50
  • I guess I could rephrase that as "what might be an industry standard" since I have no idea just how much time an average connection might take to be established, for example. – payne Sep 09 '18 at 17:54
  • @payne I don't know of any such standard. – Andreas Sep 09 '18 at 17:57