如何使用Handler.Post()通知工作线程修改UI?

时间:2013-05-24 09:48:08

标签: android multithreading

我有一个工作线程,偶尔我会使用Handler.Post()向UI线程发送更新。在某些情况下,我需要工作线程等到在UI线程上执行Handler.Post()并且视图被修改并且 UI线程被修改后,通知工作线程继续... 这是我简单的工作线程:

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();

2 个答案:

答案 0 :(得分:3)

使用带有等待和通知的同步块

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();

答案 1 :(得分:0)

如何使用Semaphore呢?

Semaphore semaphore = new Semaphore(0);
uiHandler.post(new Runnable() {
  // ... do something here
  semaphore.release();
});
semaphore.acquire();

Semaphore0许可开头。线程将在semaphore.acquire()上阻止,直到semaphore.release()(将添加许可证)被调用。