Wednesday, February 27, 2013

Simple AsyncTask Example in Android


Any User interaction on any Android application should and must response with in 5 seconds, failure to which results in ANR Dialog. Yes "Application Not Responding" Dialog with 'Wait' and 'Force Close' inputs. Asynchronous operations can also be performed using Threads in accordance with Handler and messages to update UI about the action progress.

Here we will see how AsyncTask can be incorporated to perform Synchronous operations updated the progress of operation.

Three types are used by AsyncTask, in this case datatype is a String,

AsyncTask
First param String : This type of the parameters sent to the task upon execution.
Second param : This type of the Strings contains progress units published during the background operation.
Third param Result : This strings contains the result of the background operation.
Note : when no params are required use type void.

AsyncTask, that simplifies the creation of long-running tasks that need to communicate with the user interface.
The goal of AsyncTask is to take care of thread management.
Example :
public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}

private class DownloadImageTask extends AsyncTask {
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}

A class extend AsyncTask which triggers/perform long running tasks along side in override methods of AsyncTasks.You can specify the type, using generics, of the parameters, the progress values and the final value of the task.
  • The method doInBackground() executes automatically on a worker thread
  • onPreExecute() , onPostExecute() and onProgressUpdate() are all invoked on the UI thread
  • The value returned by doInBackground() is sent to onPostExecute()
  • You can call publishProgress() at anytime in doInBackground() to execute onProgressUpdate() on the UI thread
  • You can cancel the task at any time, from any thread



No comments:

Swift Operators - Basic Part 3 (Range operators in swift)

Range Operators: Closed Range operators  Half-Open Range Operators One-Sided Ranges Closed Range Operators:  a...b It defines...