Return data from AsyncTask Android

前端 未结 3 682
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 04:09

I tried to refer similar question on SO, but didn\'t got any help.

In my android app, I\'m planning to implement Recent Quote the user has visited i.e. similar to r

3条回答
  •  再見小時候
    2021-01-05 04:49

    Essentially, AsyncTask.onPostExecute() is where you do whatever you want to do after AsyncTask's doInBackground() is executed and the execution result gets returned. This should be considered the best practice.

    When AsyncTask().execute() is called from the UI thread (note that this method must be called from the UI thread), the Android framework creates a worker thread and starts running whatever you wrote in AsyncTask.doInBackground() on this worker thread. At this point (after calling new AsyncTask().execute()), the UI thread continues to execute code after new AsyncTask().execute(). So now during run time, you have two threads (UI and worker thread) both running simultaneously.

    But where and when does the AsyncTask execution result get returned from the worker thread back to the UI thread?

    The point where your worker thread (doInBackground()) finishes and returns to the UI thread is AysncTask.onPostExecute(). This method is guaranteed to be called by the framework on the UI thread as soon as AsyncTask finishes. In other words, we don't care where and when AsyncTask.onPostExecute() gets called at run time, we just need to guarantee it will be called ultimately at some stage in the future. This is the reason why this method does not return an execution result - instead, it requires that the execution result gets passed in as the only method parameter from doInBackground().

    In addition, the Android API provides a way to return an AsyncTask execution result at coding time, AsyncTask.get():

    MyAsyncTask myAsyncTask = new MyAsyncTask();
    
    // This must be called from the UI thread:
    myAsyncTask.execute();
    
    // Calling this will block UI thread execution:
    ExecutionResult result = myAsyncTask.get();
    

    Bear in mind that AsyncTask.get() will block the calling thread's execution, and you will probably get an ANR exception if you call it on the UI thread. This is the payload of using AsyncTask.get(), by calling it on the UI thread, you are actually making your AsyncTask (worker thread) run synchronously with UI thread (by making UI thread wait). To sum up, this is doable but not recommended.

提交回复
热议问题