Jimmy
Jimmy

Reputation: 10341

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;

}

Upvotes: 5

Views: 9991

Answers (3)

Dmitry
Dmitry

Reputation: 3169

Did you try polling Thread.getState()?

Something like this:

android.os.Handler h = new Handler();
h.postDelayed(new Runnable() { 
public void run () {
      if (thread.getState() == Thread.State.TERMINATED) {
           // your code here
           return;
      }
      h.postDelayed(this, 1000);
}, 1000);

This sample should poll a thread state every second... (I didn't tested it)

Upvotes: 0

NickT
NickT

Reputation: 23873

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.

Upvotes: 3

Haphazard
Haphazard

Reputation: 10948

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.

Upvotes: 4

Related Questions