Issue
So please excuse the rookie question...
I've got an AsyncTask:
class DownloadWeather extends AsyncTask<String, Void, String>{
}
But I've noticed there's 2 ways of getting information out of it... namely using onPostExecute:
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
Or simply calling it like this from the mainActivity:
json = downloadWeather.execute(url).get();
As far as I can tell the whole purpose of an AsyncTask is to keep the user interface interactive... But won't using the second option in the MainActivity class result in the UI losing frames? If it does, why does the second option even exist?
On that same note... is there a simple way to call a function located in the MainActivity class from the onPostExecute method?
Solution
But won't using the second option in the MainActivity class result in the UI losing frames? If it does, why does the second option even exist?
Although the main purpose of AsyncTask is to facilitate the proper and easy use of the UI thread and perform background operations, there might be some usecases where get()
could be used.
Since answer to this question could be a bit arbitrary, you might disagree with my answer but some use cases in which get()
could be as follows:
There could be a case, where you would like to use a
AsyscTask
as individual task or bundle with some other tasks: Consider a scenario, where you have to download some data based on Ids. The API for Ids and data are different.i.e. you need to use one API to download Ids and one API to download data. You can create a wrapper which will useIdDownloadTask.get()
andDataDownloadtask.get()
to ensure sequential load. In case the Ids are available, then you can directly exectueDataDownloadTask.execute()
.You could also use
get()
in test suite, to create test for profiling the round-trip time taken by your web API.There could be a multi-threading situation where output of
AsyncTask
is essential for this thread before proceeding with further execution.
There are several other APIs exposed by Android which are rarely used but someone with special request could need them. I feel Google needs to be verbose so that they cater to needs of awash of developer's needs since modification for several trivial usecase could be expensive.
Answered By - Sagar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.