Mehdi Fanai Mehdi Fanai - 2 months ago 15
Android Question

How to notify worker thread that UI is modified using Handler.Post()?

I have a worker thread and occasionally i send updates to the UI Thread using

Handler.Post()
. In some cases i need worker thread to wait until
Handler.Post()
executed on UI Thread and the view is modified and after UI thread is modified, notify the worker Thread to go on...
here is my simple worker thread:

workerThread = new Thread() {
@Override
public void run() {
progressBarHandler.post(new Runnable() {
public void run() {
//Step1: which works ok
ActionModeButton.performClick();
}
}

//Step2: returns null pointer exception because ActionMode
//is not yet created and R.id.select_recording is an
//ActionMode button if I put Thread.sleep(1000); here it
//will work fine.
final View selectRecording = getActivity()
.findViewById(R.id.select_recording);
selectRecording.post(new Runnable() {
public void run() {
selectRecording.performClick();
}
});
}
}
workerThread.start();

Answer

using synchronized block with wait and notify

final Handler handler = new Handler();
    final Object lock = new Object();
    new Thread(new Runnable() {
        boolean completed = false;
        @Override
        public void run() {

            handler.post(new Runnable() {
                @Override
                public void run() {
                    synchronized (lock) {
                        //Do some stuff on ui thread 

                        completed = true;
                        lock.notifyAll();                            
                    }
                }
            });

            synchronized (lock) {
                try {
                  if(!completed)
                    lock.wait();
                }
                catch (InterruptedException e) {

                }
            }

        }
    }).start();
Comments