0

Below is the code for checking internet via broadcast receiver.

public class CheckConnection extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
        if(isOnline(context)){
            //Do Stuff
        }
        else{
            //Toast message saying "No internet"
        }

}


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

And I have say n events.For those n events I am calculating the distance between current location and destination using google distance matrix API.And also am using AsyncTask multiple times for calculating the distance.But now am confused on how to call broadcast receiver to check internet connection and call the method which calculates the distance.How to make sure whether the app is connected to internet or not all the time.

Thanks for your time.

TryingToLearn
  • 365
  • 2
  • 4
  • 15

2 Answers2

0

Couldn't you just call isOnline right before any other call that is dependent on an active internet connection, and then just wait a little bit and try again?

Simen Russnes
  • 2,002
  • 2
  • 26
  • 56
0

You don't have to use Async if you don't need to access UI. You can simply create a thread to handle internet checking with a loop and calculate the distance in it. I don't think it's a good idea to use broadcast in your case.

Stephen Lin
  • 4,852
  • 1
  • 13
  • 26