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(开发者_如何学JAVA);
mt.start();
return mt.isSentSuccessfully;
}
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.
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.
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)
精彩评论