开发者

Android, quick question from my book

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 && is开发者_开发知识库Running.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"?


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):

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.

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:

Message m = new Message();
Bundle b = new Bundle();
b.putInt("what", 5); // for example
m.setData(b);
handler.sendMessage(m);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜