A common requirement in any data driven Android app is the ability to download data asynchronously. This might be to lookup locations for a Google Maps view or to acquire dynamic app data. In order to do this you need to create a nested inner class that extends the AsyncTask class.
To do this is pretty simple:
class OuterClass {
...
class InnerClass {
...
}
}
Our inner class can now be accessed from within the outer class by calling:
InnerClass.myMethod()
In our case we want our inner class to extend the AsyncTask class so we start with:
class OuterClass {
...
class InnerClass extends AsyncTask {
...
}
}
Now there are also three sets of data which need types to be defined. These are:
- Parameters taken by the task
- Progress reporting data returned by the class
- Returned values from the task
class OuterClass {
...
class InnerClass extends AsyncTask {
...
}
}
There are also four methods that you need to know about:
- onPreExecute() – which is used to prepare the UI thread for the task.
- doInBackground(Params…) – which takes the parameters passed to the class and does the background task. E.g. downloads some data.
- onProgressUpdate(Progress…) – which tells the UI the percentage progress (integer out of 100).
- onPostExecute(Result) – which runs on the UI thread after the background task is complete.
So our class might look something like:
class OuterClass {
...
class InnerClass extends AsyncTask {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
JSONObject[] jsondata;
for (int i = 0; i < count; i++) {
try {
String data = getStringContent(urls[i]);
jsondata[i] = new JSONObject(data)
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jsondata;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(JSONObject data) {
// TODO process returned data eg:
MyApplication.setJSONData(data);
}
}
}
There are a couple of funky Java things here worth explaining here. The … notation means an array of that type so URL… url means that an array of URL’s will be passed. Similarly the square brackets in the object declaration JSONObject[]… creates an array of JSONObject objects.
Lastly we want to be able to run this task and to do this we simply run:
new InnerClass().execute(url1, url2, url3);
Where url1 etc are the parameters all of type URL.
I hope this helps someone but for way more detail see http://developer.android.com/reference/android/os/AsyncTask.html