Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to wait for Android runOnUiThread to be finished?

I have a worker thread that creates a runnable object and calls runOnUiThread on it, because it deals with Views and controls. I'd like to use the result of the work of the runnable object right away. How do I wait for it to finish? It doesn't bother me if it's blocking.

like image 371
djcouchycouch Avatar asked May 13 '11 19:05

djcouchycouch


People also ask

How do you wait for a runnable to finish?

Create an Object called lock . Then after runOnUiThread(myRunnable); , you can call lock. wait() .


2 Answers

Just scratching out the highlights

synchronized( myRunnable ) {    activity.runOnUiThread(myRunnable) ;     myRunnable.wait() ; // unlocks myRunable while waiting } 

Meanwhile... in myRunnable...

void run() {    // do stuff     synchronized(this)    {       this.notify();    } } 
like image 77
Andrew Avatar answered Sep 23 '22 17:09

Andrew


Perhaps a little simplistic but a mutex will do the job:

final Semaphore mutex = new Semaphore(0); activity.runOnUiThread(new Runnable() {     @Override     public void run() {         // YOUR CODE HERE         mutex.release();     } });  try {     mutex.acquire(); } catch (InterruptedException e) {     e.printStackTrace(); } 
like image 28
DDD Avatar answered Sep 19 '22 17:09

DDD