Tony Tony - 3 months ago 13
Android Question

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 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;
}

Answer

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.

Comments