I have a problem with AsyncTask and onPostExecute. I find that onPostExecute runs on a different thread than the main ui thread that throws a CalledFromWrongThreadException when I change any views.
I started some logging to find out which streams on PreExecute, doInBackground and onPostExecute work. I would see such a result ...
onPreExecute ThreadId: 1 doInBackground ThreadId: 25 onPostExecute ThreadId: 18
I believe that the main identifier of the ui thread is 1, and I would expect both onPre and onPost to both be executed in thread 1. I am sure that you create and also call the execute method from the ui thread (for example, onCreate of a Events).
Another thing I noticed is that in subsequent async tasks, their onPostExecute method will be launched in the same thread as the previous async onPostExecute task (in this case, thread 18).
Right now, to get around this, I am wrapping code in my onPostExecute methods when calling runOnUiThread, but I think this is hacked and would like to get a real problem.
I have no ideas! Does anyone have an understanding? I am happy to answer any questions that may help with further investigation!
EDIT:
There are two ways to run asynchronous tasks in code. I wonder if the last of these examples causes anything strange?
public class SomeActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); new SomeAsyncTask().execute(); } private class SomeAsyncTask extends AsyncTask<String, Void, Integer> { @Override public void onPreExecute() { Thread.currentThread().getId()
}
The above is similar to using AsyncTask's vanilla use, but I can still see that this question occurs even in simple cases like this. The following example uses the async task to perform other async tasks. Maybe there is something that I do not know about what happens when an asynchronous task is created that causes some strange behavior?
public class SomeActivity extends Activity implements TaskRunner.OnFinishListener { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_layout); TaskRunner taskRunner = new TaskRunner(); taskRunner.setOnFinishListener(this); taskRunner.addTask(new SingleTask()); taskRunner.addTask(new SingleTask()); taskRunner.execute(); } @Override public void onTaskFinish(List<Integer> results) {
Perhaps what is happening here is just super weird, and not at all how asynchronous tasks should be used, since it would be nice to understand the essence of the problem.
Let me know if you need more context.