AsyncTask 的 onPostExecuted 是什么时候执行的?

When is onPostExecuted of AsyncTask executed?

考虑以下示例活动:

public class ExampleActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info);

        new ExampleTask().execute("");

        // code line 1
        // code line 2
        // code line 3
        // code line 4
    }

    public class ExampleTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... address) {

            // some long-running stuff
            return "";
        }

        protected void onPostExecute(String text) {

        }
    }
}

  new ExampleTask().execute("");

我们启动一个 AsyncTask,它运行在 UI 线程之外。我们无法预测何时完成。 AsyncTaskonPostExecute 方法再次在 UI 线程上运行。

假设 AsyncTask 在执行 onCreate 方法的 code line 2 时完成。 onPostExecute方法什么时候执行?是等到 onCreate 完成还是立即执行?

我认为这个问题可以概括为 Java(或至少 Android)如何处理从主线程运行但 return 到主线程的线程以及如何 Java/Android安排两个 'competing' 的代码序列立即执行。 因此,如果答案能提供一些一般性的见解,那就太好了。

onPostExecute 将在 doInBackground 方法中的任务完成后立即调用。查看有关 AsyncTask

的详细信息

Let's say the AsyncTask is done while code line 2 of the onCreate method is being executed. When will the onPostExecute method be executed? Does it wait until onCreate is done or will it be executed immediately?

是的,它确实等待 onCreate 完成,onPostExecute 将在 onCreate 方法之后调用。

它将在 onCreate() 完成后调用,因为 UI 线程上的任何回调都是按顺序处理的。所以,首先 onCreate() 然后 onPostExecute() 但是,这似乎是一个实现细节,您不应该依赖它。

你可以在这里亲眼看到这一切: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/os/AsyncTask.java

           // that's on the background thread
line #288: return postResult(doInBackground(mParams)); 

private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        // here it sends the message to the intenral UI handler
        message.sendToTarget(); 
        return result;
    }

意思是:

AsyncTask post 向它自己的内部 UI 处理程序发送一条消息,这意味着 onPostExecute 只会在 UI 上排队的所有其他内容之后执行Looper 被处决