2

Currently I working on App which supposed to work offline and online. But there in some scenario where network in available but no internet connection. Or how can I check connection speed. If connection speed is very low it should work in offline mode. Below are the code how I am checking network availability.

public static boolean isNetworkAvailable(Context ctx) {
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();

    if (activeNetworkInfo != null) {
        if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            Log.v("Connection Type", "WI FI");
        } else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            Log.v("Connection Type", "Mobile");
        }
    }

    return activeNetworkInfo != null
            && activeNetworkInfo.isConnectedOrConnecting();
}
u_pendra
  • 908
  • 1
  • 10
  • 25
  • 1
    in this case you can set time out limit, if in that time duration data sending or receiving is successes do that else show network error and do that task for offline mode. – Manish Srivastava Nov 08 '13 at 04:49
  • 1
    ConnectivityManager will only give you if Wifi is connected or Mobile data is connected, but does not give proof of actual internet connection. In my app, I assume that if the network is available, it is connected to internet and throw notification message of any errors. I also assume that WiFi is fast internet and Mobile data is slow – Madhur Ahuja Nov 08 '13 at 04:52

3 Answers3

1

In this case you can set time out limit, if in that time duration data sending or receiving is successes do that else show network error and do that task for offline mode.

You may check see this link on stackoverflow-

how to set Http connection timeout on Android

Manish Srivastava
  • 1,649
  • 2
  • 15
  • 23
1
  public boolean isConnectingToInternet(){

    ConnectivityManager connectivity = (ConnectivityManager)YourActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
      if (connectivity != null) 
      {
          NetworkInfo[] info = connectivity.getAllNetworkInfo();
          if (info != null) 
              for (int i = 0; i < info.length; i++) 
                  if (info[i].getState() == NetworkInfo.State.CONNECTED)
                  {
                      return true;
                  }

      }
      return false;
}
AnAndroid
  • 567
  • 1
  • 5
  • 16
1

try to handle the two Timeout exception which could help you.

try
{
      //do connection process
}
catch (SocketTimeoutException e) 
{
     System.out.println(e.getMessage());
}
catch (ConnectTimeoutException e2)
{
     System.out.println(e2.getMessage());
}
krishna
  • 4,069
  • 2
  • 29
  • 56