Is there anything similar to onPreExecute and onPostExecute for traditional threads?
I used AsyncTask
before, only to switch to traditional Thread
for reasons that weren’t worth diving into for this issue.
What can I do to make something execute before and after the thread starts, similar to onPre/PostExecute?
For example, let’s say I want to display a loading circle before the thread starts and close it at the end of the thread. What should I do?
For the post-execute bit, I’m using thread.join() and it seems to fix the problem. I’m not sure if this is the solution to the problem, though, or how to do pre-execution.
Solution
What can I do to make something execute before and after the thread starts, similar to the functionality of onPre/PostExecute?
onPreExecute
() -> The statement executed before start()
is called on the Thread
onPostExecute
() -> calls runOnUiThread
() or post()
on the View
, and from your Thread
, provides a Runnable
to execute on the main application thread
How would I do that?
Ideally, you wouldn’t. The progress dialog sucks. Place a progress indicator somewhere in your UI (for example, action bar, title bar) and disable several things that users can’t safely do while your thread is running.
That is, you might display a DialogFragment
before executing a thread, and then delete that fragment after the thread completes through the mechanism described above.
For the post-execution bit, I’m using thread.join() and it seems to do the trick.
Disgusting. This will block any thread you’re on, and if that’s the main application thread, that’s really bad.
Update
runOnUiThread()
example:
new Thread() {
public void run() {
do cool stuff
runOnUiThread(new Runnable() {
public void run() {
do other cool stuff quickly on the main application thread
}
);
}
}).start();