Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waiting for thread to finish without blocking UI thread

Im running a Thread inside methode and i want to return a value once the thread finish, the problem that i tried to do join() but that blocks the UI thread. How could i wait for the thread to finish and then return the value without blocking the UI thread ?

Boolean foo(){

myThread mt = new myThread();
mt.start();     
return mt.isSentSuccessfully;

}
like image 812
Jimmy Avatar asked Apr 25 '11 13:04

Jimmy


2 Answers

You can use Android's AsyncTask for that. http://developer.android.com/reference/android/os/AsyncTask.html When I use it, I put the background task in a class that extends AsyncTask and overwrite the onPreExecute() and onPostExecute(..) methods to show/hide the ProgressDialog. It works quite nicely.

like image 74
Haphazard Avatar answered Sep 27 '22 21:09

Haphazard


If you really don't want to use the AsyncTask, then you might like to define a Handler

then in your background thread send a message to the main thread when the background job finishes with something like:

ActivityMainThreadClassName.this.myUpdateHandler.sendMessage(m);

where myUpdateHandler is the handler you created.

like image 39
NickT Avatar answered Sep 27 '22 22:09

NickT