Search code examples
androidandroid-wifi

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();

Solution

  • 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" />