- doInBackground: Code performing long running operation goes in this method. When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
- onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
- onPreExecute: This method is called before doInBackground method is called.
- onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.
AsyncTask is a generic class, it uses 3 types: AsyncTask<Params, Progress, Result>.
- Params – the input. what you pass to the AsyncTask
- Progress – if you have any updates, passed to onProgressUpdate()
- Result – the output. what returns doInBackground()
Below is the sample code for AsyncTask
displayProgressBar is a function used to display a progressbar when the operation is running
Code: Select all
private class PostTask extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
displayProgressBar("Downloading...");
}
@Override
protected String doInBackground(String... params) {
String url=params[0];
// Dummy code
for (int i = 0; i <= 100; i += 5) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return "All Done!";
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
updateProgressBar(values[0]);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dismissProgressBar();
}
}
The AsyncTask is started by using the execute command along with parameters(Optional)
Code: Select all
new PostTask().execute("http://forum.androidappmasters.com");
in this example the parameter is not used anywhere.it is just to show as an example