Skip to content Skip to sidebar Skip to footer

Perform Network Operation To Check If User Has Internet Connection With Async Task

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 i

Solution 1:

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

privateclassNetworkInAsyncextendsAsyncTask<String, Void, Boolean> {

    privateContext context;
    privateActivity activity;

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


    @OverrideprotectedvoidonPreExecute() {
    }

    @OverrideprotectedvoidonPostExecute(Boolean result) {
        // Do something with the result here 
    }

    @OverrideprotectedBooleandoInBackground(String... params) {
        if (isNetworkAvailable()) {
            try {
                HttpURLConnection urlc = (HttpURLConnection)
                (newURL("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 trueshowAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
        }
        returnfalse;
    }
}

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.

Solution 2:

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

call test();

privatevoidtest() {
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.

Post a Comment for "Perform Network Operation To Check If User Has Internet Connection With Async Task"