-2

Why the modification of the graphical interface is performed in a seperate method (onPostExecute) and not executed by the background thread ?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
El.K Ibrahim
  • 53
  • 1
  • 8
  • The question is too broad. If you shared some of your research and stuck, meanwhile having this question, that'd be fine. However, SO is not the best place to ask such. – TEH EMPRAH Jun 13 '18 at 11:29
  • @TEHEMPRAH please take a look at the marked answer where my question is comprehend and well explained. – El.K Ibrahim Jun 13 '18 at 13:11
  • Please take a look at the mark above then, asking to clarify YOUR specific problem. Thank you. – TEH EMPRAH Jun 15 '18 at 06:41

1 Answers1

1

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

Anoop
  • 993
  • 6
  • 16