I wrote AsyncTask for short background operations in android for quite a while and had a very simple question. If I started AsyncTask from a separate thread, and not from the main UI thread, my onPreExecute() and onPostExecute will still be called in the UI thread or the thread that I started AsyncTask . I'm curious because I was not able to show the popup inside the onPreExecute() method when I started it from some other thread.
EDIT 2
I tried writing this simple activity to try: public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { final TestAsyncTask task = new TestAsyncTask(); task.execute(); } }).start(); } private class TestAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... voids) { return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); Toast.makeText(MainActivity.this, "Yo!", Toast.LENGTH_LONG).show(); } } }
This is normal. But when I run the application with the following code:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Thread(new Runnable() { @Override public void run() { final TestAsyncTask task = new TestAsyncTask(); task.execute(); } }).start(); } private class TestAsyncTask extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { super.onPreExecute(); Toast.makeText(MainActivity.this, "Yo!", Toast.LENGTH_LONG).show(); } @Override protected Void doInBackground(Void... voids) { return null; } } }
The following error failed:
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
as one of the lines in the stack trace.
source share