Skip to content Skip to sidebar Skip to footer

Correct Use Of Asynctasks And Handle Objects Needed By A View And Activity

So I am currently writing an App and have a few questions about how to deal with AsyncTasks. I describe my problem as detailed as I can. I have the following classes: MainActivity

Solution 1:

Well, from the AsyncTask docs you can gather this:

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

So what I would suggest for you is to use two AsyncTasks to do your geo and server (one for each) work in the doInBackground(Params...) method and return the value to your MainActivity in the onPostExecute(Result) method. Also, keep your MainActivity aware of the progress by using the onProgressUpdate(Progress..) method.

When they are done, you can choose to use another AsyncTask to do the calculations if they stall the UI thread noticeably. Use the same method of execution for it.

When this is all done you are ready to draw a view... (I think is what you're saying)

Have a default view load before you start the calculations that says "Loading..." or whatever. Have another view that is not visible ready for when you are ready to display your calculated things and just set it visible when it is ready to be drawn on.

Post a Comment for "Correct Use Of Asynctasks And Handle Objects Needed By A View And Activity"