AsyncTask in android

Frequently used code samples and tutorials
vivekkalady
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> {
   @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

Return to “Tutorials & Examples”

Who is online

Users browsing this forum: No registered users and 1 guest

cron