Android,我书中的快速问题
我是一个通过书本学习 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 中将鼠标悬停在上面会显示一条听起来像是胡言乱语的消息。
它试图“获取”什么信息?
I am a noob learning Android via a book, i have a quick question. My book code is pretty simple and looks like this:
My handler:
Handler handler=new Handler() {
@Override
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
}
};
My thread:
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
}
}
});
My question is here:
handler.sendMessage(handler.obtainMessage());
What the heck is "handler.obtainMessage()" ?
Doing a mouse over in Eclipse gives me a message that sounds like gibberish.
What message is it trying to "obtain"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如文档中所述,它获取消息池中的消息而不是创建新消息。 (无论如何,您需要向处理程序发送消息):
我将尝试详细说明:
您向处理程序发送一条消息。该消息被添加到处理程序的线程队列中并在原始线程上进行处理。您需要向它发送一条消息,尽管它使用的消息中没有任何具体内容(根据您的处理程序代码),因此您只需发送一条空消息,但不是为新消息分配内存,而是从消息池,速度更快。
希望这能让事情变得更清楚。
关于如何用 int 设置消息:
As described in the docs, it obtains a message from the message pool instead of creating a new one. (you need to send a message to the handler anyway):
I'll try to elaborate:
You send a message to the handler. The message is added to the handler's thread queue and processed on the original thread. You need to send it a message, though you have nothing specific in the message that it uses (according to your handler code) so you just send an empty message, but instead of allocating a memory for a new message, the message is taken from the message pool, which is faster.
Hope this makes things clearer.
Regarding how to set a message with an int: