gpt4 book ai didi

android - 如何将 Runnable 对象传递给处理程序?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:00 25 4
gpt4 key购买 nike

我正在通过一本书学习,它给了我这个例子:

Handler handler=new Handler() { 
@Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
}
};

Thread background=new Thread(new Runnable() { 
public void run() {
try {
for (int i=0;i<20 && isRunning.get();i++) {
Thread.sleep(500);
handler.sendMessage(handler.obtainMessage());
}
} catch (Throwable t) {
// just end the background thread
}
}
});

效果很好。但是,在书的更下方,它说:

If you would rather not fuss with Message objects, you can also pass Runnable objects to the Handler, which will run those Runnable objects on the activity UI thread. ...you can use those same methods on any View (i.e., any widget or container). This slightly simplifies your code, in that you can then skip the Handler object.

但是没有给出如何通过 Runnable 对象执行此操作的示例。有人有例子吗?

最佳答案

是这样的:

Handler h = new Handler();

Thread background=new Thread(new Runnable() { 
public void run() {
try {
for (int i=0;i<20 && isRunning.get();i++) {
Thread.sleep(500);
handler.post(new Runnable() {
public void run() {
bar.incrementProgressBy(5);
}
});
}
}
catch (Throwable t) {
// just end the background thread
}
}
});

关于android - 如何将 Runnable 对象传递给处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6804862/

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