AsyncTask in android

Frequently used code samples and tutorials
Site Admin
Posts: 35
Joined: Tue Nov 18, 2014 2:39 pm

AsyncTask in android

Postby vivekkalady » Sat Nov 22, 2014 11:51 am

AsyncTask has four steps:

  • 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>.

  1. Params – the input. what you pass to the AsyncTask
  2. Progress – if you have any updates, passed to onProgressUpdate()
  3. 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> {
   protected void onPreExecute() {
   protected String doInBackground(String... params) {
      String url=params[0];
      // Dummy code
      for (int i = 0; i <= 100; i += 5) {
        try {
        } catch (InterruptedException e) {
      return "All Done!";
   protected void onProgressUpdate(Integer... values) {
   protected void onPostExecute(String result) {

The AsyncTask is started by using the execute command along with parameters(Optional)

Code: Select all

new PostTask().execute("");

in this example the parameter is not used is just to show as an example

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest