Sashi Kiran
Sashi Kiran

Reputation: 306

Determine if Internet connection is available through wifi in android

I am developing an app that will be working offline also.

My scenario is this:
I have two WIFI devices in range to my mobile. Device1 has internet connection, where as the Device2 is like a WIFI-Hotspot, which sends only few data that my application will be using.

When I am connected to Device2 I start collecting the data and save in the mobile SQLite. When I change to Device1 and start have an internet connection I will be syncing the data to my server through an API call.

The case is when ever I have access to the internet I should be able to make that API call.

How do I achieve this?

I went through many articles and all I got is the connection status of the wifi device and not the internet connection.

NOTE: Please don't ask me to try this code:

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);<br/>
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();<br/>
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

Upvotes: 0

Views: 211

Answers (2)

Rissmon Suresh
Rissmon Suresh

Reputation: 14073

The Only thing u can do is

if(isNetworkAvailable}{
     if(isHostAvailable){
      //perform your communication
     }
}

//Check your server connectivity status

 private boolean isHostAvailable() {
    URL url = new URL("http://stackoverflow.com");// specify the url
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
    System.out.println(conn.getResponseCode());
     if(conn.getResponseCode().equalsIgnoreCase("200")){
          return true;
     }

    return false;
 }

//Check for device connectivity status

 private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

You will also need:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Upvotes: 1

Simon
Simon

Reputation: 1190

You can just try to establish a TCP connection to a remote host:

public boolean hostAvailable(String host, int port) {
  try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress(host, port), 2000);
    return true;
  } catch (IOException e) {
    // Either we have a timeout or unreachable host or failed DNS lookup
    return false;
  }
}

And check it:

boolean online = hostAvailable("www.your-service.com", 80);

Upvotes: 1

Related Questions