u_pendra
u_pendra

Reputation: 948

Network present but no Internet connection

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

Upvotes: 2

Views: 608

Answers (3)

Manish Srivastava
Manish Srivastava

Reputation: 1659

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

Upvotes: 1

krishna
krishna

Reputation: 4099

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

Upvotes: 1

AnAndroid
AnAndroid

Reputation: 567

  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;
}

Upvotes: 1

Related Questions