我是一个通过书本学习 Android 的菜鸟,我有一个快速的问题。我的图书代码非常简单,如下所示:
我的处理程序:
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(1000);
handler.sendMessage(handler.obtainMessage());
}
}
catch (Throwable t) {
// just end the background thread
}
}
});
我的问题在这里:
handler.sendMessage(handler.obtainMessage());
“handler.obtainMessage()”到底是什么?
在 Eclipse 中将鼠标悬停在上面会给我一条听起来像是乱码的消息。
它试图“获取”什么消息?
最佳答案
如所述in the docs ,它从消息池中获取一条消息,而不是创建一条新消息。 (无论如何你都需要向处理程序发送消息):
Returns a new Message from the global message pool. More efficient than creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this). If you don't want that facility, just call Message.obtain() instead.
我会尽量详细说明:
您向处理程序发送消息。消息被添加到处理程序的线程队列中并在原始线程上进行处理。您需要向它发送一条消息,尽管它使用的消息中没有任何具体内容(根据您的处理程序代码),因此您只需发送一条空消息,而不是为新消息分配内存,该消息取自消息池,速度更快。
希望这能让事情变得更清楚。
关于如何使用 int 设置消息:
Message m = new Message();
Bundle b = new Bundle();
b.putInt("what", 5); // for example
m.setData(b);
handler.sendMessage(m);
关于Android,我书中的快速问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6804668/