4

In my application fully depends on network, ie, i get the data (Image with Text) from web and just display in my layout. For this my major issue is how to handling the network connection. I used the following code to check, whether the device is connected to the network or not.

    public static boolean hasConnection() {
    ConnectivityManager cm = (ConnectivityManager) MbridgeApp.getContext().getSystemService(
        Context.CONNECTIVITY_SERVICE);

    NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    if (wifiNetwork != null && wifiNetwork.isConnected()) {
      return true;
    }

    NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    if (mobileNetwork != null && mobileNetwork.isConnected()) {
      return true;
    }

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected()) {
      return true;
    }

    return false;
  }
  1. This piece of code gives the information about if the device is connected to network or not.
  2. My problem will arise, some time the network is connected but the signal strength is too low, this situation my application takes more time (data fetched from API), after a long time the application is freeze or crashed.
  3. is it possible to set minimum rage of signal strength, if it goes below the range, i just notify the toast message to the user.
Aerrow
  • 12,086
  • 10
  • 56
  • 90

1 Answers1

1

You may set a timeout for your http calls, while using them on seperate threads, and show some progress while loading for user friendly ui.

EDIT

You can use AsyncTask to fetch data, and there is no need to check for connection, as the AsyncTask will complete in no time if the device is not connected.

final ServerHit serverHit = new ServerHit(this);
serverHit.execute(url);
// set a timeout
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (serverHit.getStatus() == AsyncTask.Status.RUNNING)
                    serverHit.cancel(true);
            }
        }, timeout);
Ahmad Dwaik 'Warlock'
  • 5,953
  • 5
  • 34
  • 56