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 Executor
, ThreadPoolExecutor
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
Params
, Progress
and Result
, and 4 steps, called onPreExecute
, doInBackground
, onProgressUpdate
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
- onPreExecute()
- doInBackground()
- onProgressUpdate()
- 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:
Params
, the type of the parameters sent to the task upon execution.Progress
, the type of the progress units published during the background computation.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"); } }
You can download each of example from my Git link. https://github.com/khetiyachintan
ReplyDeletei want to play some Audios in my App with Asynctask. can you help me with this?
ReplyDeleteSimple and Precise
ReplyDeleteThank you sachin. :)
ReplyDelete@Chintan Khetiya, your project of github is professional! :D
ReplyDeleteHello Zahra, Thanks for your feedback appreciate it.
ReplyDelete