0

I am getting below exception

android.os.NetworkOnMainThreadException

because I don't use an async task to make the particular network operation. I have searched for this, but it got me so confused. Could someone make it work with async task and the particular functions?

Below are two functions i use :

1) isNetworkAvailable()

private boolean isNetworkAvailable() {

    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;

}

2) hasInternetAccess(Boolean showMessage)

When i want to display a toast i call this function, setting the parameter to true.

public boolean hasInternetAccess(Boolean showMessage) {

    if (isNetworkAvailable()) {
        try {
            HttpURLConnection urlc = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 204 &&
                    urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.w("connection", "Error checking internet connection", e);
        }
    } else {
        if(showMessage) // If i want to show the toast, it's true
            showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
    }
    return false;
}
Vickyexpert
  • 3,147
  • 5
  • 21
  • 34
Antonios Tsimourtos
  • 1,676
  • 1
  • 14
  • 37

2 Answers2

1

This is how you can use an AsyncTask by creating an inner class which extends AsyncTask.

private class NetworkInAsync extends AsyncTask<String, Void, Boolean> {

    private Context context;
    private Activity activity;

    NetworkInAsync(Activity activity) {
        this.context = activity.getApplicationContext();
        this.activity = activity;
    }


    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // Do something with the result here 
    }

    @Override
    protected Boolean doInBackground(String... params) {
        if (isNetworkAvailable()) {
            try {
                HttpURLConnection urlc = (HttpURLConnection)
                (new URL("http://clients3.google.com/generate_204")
                        .openConnection());
                urlc.setRequestProperty("User-Agent", "Android");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                return (urlc.getResponseCode() == 204 &&
                urlc.getContentLength() == 0);
            } catch (IOException e) {
                Log.w("connection", "Error checking internet connection", e);
            }
        } else {
            if(showMessage) // If i want to show the toast, it's true
            showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
        }
        return false;
    }
}

You can execute the AsyncTask as follows

new NetworkInAsync(this).execute();

I would still recommend you go through the docs here to clarify yourself how AsyncTask works in Android.

Gaurav Sarma
  • 2,248
  • 2
  • 24
  • 45
  • How should i call this? and i want it to return a boolean, should i change something in -> extends AsyncTask? – Antonios Tsimourtos Sep 03 '16 at 11:21
  • Trying to make it work, give me some time, could i call this line( new NetworkInAsync(this).execute() ) in an "if" statement returning true or false? – Antonios Tsimourtos Sep 03 '16 at 11:34
  • Its an asynctask so you can call it anywhere but it will return the result inside onPostExecute after the operation is completed inside doInBackground – Gaurav Sarma Sep 03 '16 at 11:38
  • currently i can't use boolean, it has to be Boolean, and when i change this it gives me "Method does not override method from it's superclass" in onPostExecute – Antonios Tsimourtos Sep 03 '16 at 11:43
  • now it doesn't have an error in async task, but in the line that i call async task which is in an if statement, if ( new NetworkInAsync(this).execute() ) {code} it says required Boolean, found android.os.AsyncTask – Antonios Tsimourtos Sep 03 '16 at 11:48
  • See its an an AsyncTask you can't use it like that it will return the Boolean result inside the onPostExecute and you can do your if check there you just call this new NetworkInAsync(this).execute(); where ever you want and use the logic check inside onPostExecute – Gaurav Sarma Sep 03 '16 at 11:52
  • You are welcome i am glad i was able to help. Please upvote the answer as well. Regards – Gaurav Sarma Sep 03 '16 at 12:07
0

The code should work when you call it from AsyncTask's doInBackground method

call test();

private void test() {
HttpURLConnection urlc = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());

            urlc.setConnectTimeout(1500);
            urlc.connect();
}

You can check the network connection before making the call, but any how, you should catch the exception in TimeOut exception. So I dont think, that you have any much benifit to check the connectivity before making the call.

Jithu
  • 1,478
  • 1
  • 13
  • 21