In this tutorial we will set up the URLConnection and also test the AsyncTask by using the URLConnection to download an image file from the Internet. The code for the URLConnection will be placed inside the doInBackground method of the ourAsyncTask subclass set up in the last tutorial.

First of all, we need to add a permission to the Android Manifest to allow Internet access:

"params" has been changed to "url" to reflect better what we are doing in that we are passing a URL to the method. The three dots indicate that the parameters are passed as an array or "varargs" meaning there can be more than one element. There is only one URL so it is identified as url[0]. url[0] is passed into the method that we will define that executes the URLConnection code. We will call this method downloadBitmap. Finally, we need to return the bitmap rather than null.

We can now turn our attention to the downloadBitmap method. We first need to initialize some objects.

Bitmap bitmap = null;InputStream inputStream = null;URL url = null;

Within a try and catch, we then need to set the url object to the actual URL of the file to download.

url = new URL(stringUrl);

We then need to create an object of the HttpURLConnection object and inform it of the url.