0

I have class which implements runnable. The purpose of this class is to check availability of service:

public class InternetServiceAvailability implements Runnable {

private volatile boolean available;

@Override
public void run() {

    available = false;

    try {
        HttpURLConnection connection =
                (HttpURLConnection) new URL("https://www.google.com").openConnection();
        connection.setConnectTimeout(3000);
        connection.setReadTimeout(1000);
        connection.setRequestMethod("HEAD");

        int responseCode = connection.getResponseCode();

        if (200 <= responseCode && responseCode <= 399) {
            available = true;
        }
    } catch (IOException exception) {
        exception.printStackTrace();
    }
}

public boolean isAvailable() {

    return available;
}

}

Then I want to call this class from let's say setOnClickListener event

 InternetServiceAvailability isa = new InternetServiceAvailability();
 sa.run();

 if (isa.isAvailable())
 { // do something here }

Running this I'm getting error:

android.os.NetworkOnMainThreadException

How to solve this without using AsyncTask?

Another question regarding to this is it better to AsyncTask? What you prefer in practice?

Josef
  • 2,648
  • 5
  • 37
  • 73
  • You might want to read more about how asynchronous logic works. I recommend the docs for Runnable and Thread, as well as general asynchronous logic and callbacks. – TheWanderer Dec 06 '18 at 22:03
  • There are plenty of solutions in the duplicate question, not all of which involve `AsyncTask`. – CommonsWare Dec 06 '18 at 22:41

0 Answers0