Tuesday 28 May 2013

Asynctask android example - Part 1

Hello guys , here i will try to explain the concept of the Asynctask  in android.

Class Overview


AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as ExecutorThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.

Rules:




  • The AsyncTask instance must be created in UI thread.

  • .execute must be invoked on the UI thread.

  • Never call  objMyTask.onPreExecute(), objMyTask.doInBackground(), objMyTask.onProgressUpdate(),  objMyTask.onPostExecute manually.

  • The AsyncTask can be executed only once (an exception will be thrown if a second execution is attempted.)


Method of AsynTask

  1. onPreExecute()

  2. doInBackground()

  3. onProgressUpdate()

  4. onPostExecute()




  • onPreExecute-This method is called first when you start AsyncTask using objAsync.execute().And mostly this method is use for initializing dialog(ProgressDialog,CustomDialog) and showing.



  • doInBackground-The main purpose of AsyncTask is accomplished by this method.Any non-UI thread process is running in this method.Such as Rss Feed Reader,Image and video Uploading and Downloading.You cant handle your View in this method.Because this method is non-UI thread.While any background process is running if you want to handle UI therea are  onProgressUpdate method. after completion of process this method send result to OnPostExecute.



  • onProgressUpdate-While backgrounding task is running ,you can handle your UI using this method .Such as status of downloading or uploading task.and this method is called from  doInBackground.Using publishProgress() you can call onProgressUpdate method to update UI while process is running.



  • onPostExecute -This method is called after the background computation finishes.The result of background process in passed in this method as parameters.And now you can dismiss progress dialog ,to indicate that background task is completed.



You can cancel AsyncTask using objAsyncTask.cancel().then you just check in doInBackground,




AsyncTask's generic types (Type of Parameters)


The three types used by an asynchronous task are the following:

  1. Params, the type of the parameters sent to the task upon execution.

  2. Progress, the type of the progress units published during the background computation.

  3. Result, the type of the result of the background computation.


Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:




See Example





 
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
private class DownloadFilesTask extends AsyncTask < URL, Integer, Long > {
    protected Long doInBackground(URL...urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int)((i / (float) count) * 100));
            // Escape early if cancel() is called
            if (isCancelled()) break;
        }
        return totalSize;
    }
 
    protected void onProgressUpdate(Integer...progress) {
        setProgressPercent(progress[0]);
    }
 
    protected void onPostExecute(Long result) {
        showDialog("Downloaded " + result + " bytes");
    }
}
 
 

private class DownloadFilesTask extends AsyncTask < URL, Integer, Long > {
    protected Long doInBackground(URL...urls) {
        int count = urls.length;
        long totalSize = 0;
        for (int i = 0; i < count; i++) {
            totalSize += Downloader.downloadFile(urls[i]);
            publishProgress((int)((i / (float) count) * 100));
            // Escape early if cancel() is called
            if (isCancelled()) break;
        }
        return totalSize;
    }

    protected void onProgressUpdate(Integer...progress) {
        setProgressPercent(progress[0]);
    }

    protected void onPostExecute(Long result) {
        showDialog("Downloaded " + result + " bytes");
    }
}


6 comments:

  1. You can download each of example from my Git link. https://github.com/khetiyachintan

    ReplyDelete
  2. i want to play some Audios in my App with Asynctask. can you help me with this?

    ReplyDelete
  3. Simple and Precise

    ReplyDelete
  4. Francis Rodrigues19 October 2015 at 09:12

    @Chintan Khetiya, your project of github is professional! :D

    ReplyDelete
  5. Hello Zahra, Thanks for your feedback appreciate it.

    ReplyDelete