Reputation: 22028
Consider the following example Activity:
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) {
}
}
}
With
new ExampleTask().execute("");
we start an AsyncTask
which runs off the UI thread. We can not predict when it will be finished. The AsyncTask
's onPostExecute
method runs on the UI thread again.
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?
I think this question could be generalized to how Java (or at least Android) handles Threads that run off the main thread but return to the main thread and how Java/Android schedules two sequences of code that are 'competing' for immediate excution. Thus it would be nice if an answer would provide a little general insight.
Upvotes: 2
Views: 165
Reputation: 1385
onPostExecute will be called, immediately after the task completion in the doInBackground method. see details about 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?
Yes it does wait for onCreate completion, onPostExecute will be called after the onCreate method.
Upvotes: 0
Reputation: 39836
you can see it all for your self here: 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;
}
that means:
the AsyncTask post a message to its own internal UI handler, that means that onPostExecute
will only be executed after everything else that is queued on the UI Looper gets executed
Upvotes: 2
Reputation: 48272
It will be called after onCreate()
finishes because any callbacks on the UI thread are processed sequentially. So, first goes onCreate()
then onPostExecute()
However, it seems, this is an implementation detail and you should not rely on that.
Upvotes: 1