A good strategy for checking connection?

In my project, I have 6 activities and 4 fragments. Just 1 of them is not using internet connection. All the buttons, social network api's bla bla bla using internet. So, if we count, at least 60 lines of code can give fatal error if there is no connection.

Using a checkConnection method for all these lines sounds bad for me. So, the question is; how and where should I use this connection checker? Anyone has a good strategy?

EDIT: My connection checker is very simple. Just checks when its called and if there is no connection; says "no connection" and returns previous activity.

Upvotes: 0

Views: 93

Answers (2)

Israel Tabadi
Israel Tabadi

Reputation: 574

I would use a wrapper method for any web base endpoint and write this code once there, the method should return a Boolean or an Enum value to the UI for you to handle these situations and tell the user what is wrong if something is (like no connection, low connection etc..)

Upvotes: 1

matghazaryan
matghazaryan

Reputation: 5896

public class ConnectionDetector {

    public static boolean isConnectingToInternet(Context _context){
        ConnectivityManager connectivity = (ConnectivityManager) _context.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;
    }

    public static boolean isConnectedToWIFI(Context context){
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mWifi.isConnected()) {
            return true;
        }
        return false;

    }
}

Upvotes: 1

Related Questions