0

I have to implement a function that controls the presence of the internet connection, I need to know precisely if you can browse and not know if you are connected or not to the wifi or data.

There may be cases where you are connected to a network but you can not browse, for example when you connect to an open wifi network (eg Mc Donalds) but to navigate you need to login, the connection available but you are not able to browse.

In that case I would be enough to take advantage of the set timeout (but it is never considered).

I tried to implement different functions but I can not get the desired result, for example:

public boolean checkConnection() {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    boolean response;
    if (netInfo != null && netInfo.isConnected()) {
        try {
            URL url = new URL("http://www.google.it");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(1000);
            conn.connect();
            response = conn.getResponseCode() == 200;
            conn.disconnect();
        } catch (Exception e) {
            response = false;
        }
    } else {
        response = false;
    }
    return response;
}

Another function:

public boolean isInternetAvailable(String address, int port, int timeoutMs) {
    try {
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress(address, port);

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

        return true;

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

This functions never takes the timeout into consideration.

How i can solve my problem ??

**************** EDIT 1 ****************

I'm testing the code on a tablet connected to a network via wifi, through the firewall I blocked all connections in order to simulate the situation described in the ever question. Using the codes suggested to me you notice that the timeout value is never respected, the application goes in exception:

Exception: java.net.UnknownHostException: Unable to resolve host "www.google.com": No address associated with hostname.

The real problem is that all these functions take too long to tell me that there is no connectivity, I would need a function that responds in 1/2 sec

Mattia
  • 1,057
  • 2
  • 17
  • 33

3 Answers3

1
1.public void checkOnlineState() {
    ConnectivityManager CManager =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = CManager.getActiveNetworkInfo();
    if (NInfo != null && NInfo.isConnectedOrConnecting()) {
        if (InetAddress.getByName("www.xy.com").isReachable(timeout))
        {  
         // host reachable  
        }
         else
         {    
         // host not reachable  
         }  
    }
    return;
}
   you can check whether you can access url or not by this code 
Mohit Hooda
  • 273
  • 3
  • 9
  • Look my edited question :) – Mattia Mar 08 '18 at 11:02
  • Please check my edited answer – Mohit Hooda Mar 08 '18 at 11:19
  • I'm testing the code on a tablet connected to a network via wifi, through the firewall I blocked all connections in order to simulate the situation described in the ever question. Using the codes you have suggested to me you notice that the timeout value is never respected, the application goes in exception: Exception: java.net.UnknownHostException: Unable to resolve host "www.google.com": No address associated with hostname. The real problem is that all these functions take too long to tell me that there is no connectivity, I would need a function that responds in 1/2 sec – Mattia Mar 08 '18 at 11:25
1

The easiest way to check if you have output internet connectivity is to ping some random server (www.google.com could be a good example):

InetAddress.getByName("www.google.com").isReachable(5000)
moictab
  • 959
  • 6
  • 27
-1

You could do something else entirely.

Have a service that is always running on a server and make sure you have the url for that service.

Call that service from your app everytime you want to check your connection. Check the response code of that service or maybe have it return something to you. Depending on the result code or on the data the service returns, you can conclude if you have a working internet connection or not.

There are perhaps easier ways to do what you are asking but this one will definitely work.

Stephen Docy
  • 4,738
  • 7
  • 18
  • 31