0

I've researched most of the questions here but did not find a viable solution.

I'm designing an app that highly uses internet connection. I permanently need to request/receive information from a web service.

I've tried sourounding all code that uses internet with

    try
    {
       //use of internet here
    }
   catch (Exception e)
   {
          //Alert dialog that states internet connection is down
   }

but this doesn't seem to work. The exception is not catched here for some reason.

I've tried a workaround, a solution i found here. Use of:

 public static boolean isOnline(Context context) {
    ConnectivityManager cm =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

And use it like :

        if (Utilities.IsOnline(context))
         {
          //Code that uses internet
         }

What happens if the connection is lost right after the IsOnline check? How can i treat this case? Thank you!

Dan Dinu
  • 32,492
  • 24
  • 78
  • 114
  • Consider how your network connection is affecting the battery life of your application. If you are using the network heavily, it is worth taking a look at the ARO tool that will show you if you are caching data correctly, it could make a big difference to the performance of your application http://developer.att.com/aro – Rod Burns Oct 05 '12 at 17:52

1 Answers1

1

The only way to check if the internet went down after your isOnline check is to register a BroadcastReceiver that listens to network connection changes. There is a full-code example of that in this answer.

I would suggest, if you are not already doing this, is running your code in an AsyncTask so it can run its own loop (or series of statements) and check the connection status each loop/iteration/computation and stop if disconnected.

Community
  • 1
  • 1
Cat
  • 66,919
  • 24
  • 133
  • 141