AsyncTask class is specially designed in Android to handle processes which takes time to complete, and to make it independent from the user interface. For example, suppose in an application, if we want to load some content from the web when the user clicks a button, we can use AsyncTask. And if we don’t handle it properly, the time taking web fetch will block the user interface and the user might feel the application is not very responsive. AsyncTask is capable of taking such time consuming tasks into the background and execute it as a separate thread. AsyncTask provides methods to update the UI with progress information about the task as well. AsyncTask has the following methods.
- doInBackground - It will do the real task using an independent thread - we can also usepublishProgress from inside this method to trigger the onProgressUpdate method.
- onProgressUpdate - It can be used to update the user interface and it is triggered bypublishProgress from the doInBackground method.
- onPostExecute - Once the doInBackground finished, this method gets fired, and it can update the user interface with the result retrieved from the task being just carried out.
Here is a very simple example in which, I use an AsyncTask in my main class to do a time consuming web fetch. I have not included the code to do the real web fetch, which is out of context here.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
|
In this example I used an HTML parser class which is defined in another file. Developers can use any methods for doing this. In the parser class, I had a method named getDataFromWeb() which does nothing but the time consuming data fetch from the web. I’ve not use the publishProgress()method in this example since there is only one data fetch required. You can work on this code to develop your own AsyncTask applications. :)
No comments:
Post a Comment