Android,我书中的快速问题

标签 android multithreading messaging

我是一个通过书本学习 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/

相关文章:

android - 日期更改为过去日期时未收到日期更改的广播接收器

Android:绘制自定义形状

android - 滚动 ListView 变化

java - 任何单线程程序如何成为有效的多线程程序?

c# - 如何触发依赖于其他 2 个或更多并行事件完成的事件?

iOS 实现消息系统

android - 当用户按下后退按钮然后按下最近的应用程序按钮时, Intent 数据未清除

python - 如何使用分而治之的多线程?

java - 如何在特定线程上运行我的代码?

java - 是否有更有效的方法来为 JMS 创建大量消息使用者列表?