Issue
Why the modification of the graphical interface is performed in a seperate method (onPostExecute) and not executed by the background thread ?
Solution
User Interface is composed of Views and ViewGroups. These are created and manipulated in UI thread aka Main Thread. This is the only thread allowed to create and modify views. Ant attempt to do any UI related operation from a non-UI thread will throw an exception. AsyncTask have methods like onPostExecute
, onPreExecute
, onProgressUpdate
to cater most common scenarios which arises with background processing.
I will try to explain the usecase with the simple example of Downloading a file using an async task.
onPreExecute - will be called before the background processing starts. So the progress bar for showing download progress can be made visible here. Then the doInBackground()
will be invoked and download starts.
onProgressUpdate - This method is invoked whenever publishProgress()
is called from doInBackground()
. Since doInBackground()
runs in different thread than UI thread, view cannot be updated to reflect the download progress. So doInBackground()
will call publishProgress()
with the progress of download. publishProgress()
invokes onProgressUpdate()
in UI thread and UI can be updated from here. publishProgress()
can be called in a regular interval like 30 seconds or 1 minute to continuously update the progress
onPostExecute - Once the download is completed or the background task, onPostExecute
will be invoked and this runs in UI thread. Here we can hide the progress and update UI to indicate download is complete.
Hope this clears why there is AsyncTask have those methods to update UI
Answered By - Anoop
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.