gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 08:59:06 24 4
gpt4 key购买 nike

我有一个工作线程,偶尔我会使用 Handler.Post() 向 UI 线程发送更新。在某些情况下,我需要工作线程等待,直到 Handler.Post() 在 UI 线程上执行 and View 被修改并且 after UI 线程是修改后,通知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();

最佳答案

使用带有等待和通知的同步块(synchronized block)

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

关于android - 如何通知工作线程使用 Handler.Post() 修改了 UI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16732101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com