Android的处理器消息 [英] Android, Handler messaging

查看:166
本文介绍了Android的处理器消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些非常简单的code做处理程序:

I have some very simple code to do with handlers:

 Handler seconds=new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
      bar.incrementProgressBy(5); 
      tView1.setText("r:"+msg);
    } 
  }; 

和我的主题:

Thread seconds_thread=new Thread(new Runnable() { 
              public void run() { 
                try { 
                  for (int i=0;i<20 && isRunning.get();i++) { 
                    Thread.sleep(1000); 

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



                  } 
                } 
                catch (Throwable t) { 
                  // just end the background thread 
                } 
              } 
            }); 

正如你可以在上面看到我试图改变价值什么的消息,所以我可以做基于消息不同的事情,但根据 tView1.setText(R+味精)什么不更改到5的值:(
它是只显示什么= 0

As you can see above i am trying to change the value of "what" in the message, so i can do different things based on the message, but according to "tView1.setText("r:"+msg)" the value of "what" is not changing to 5 :(
it is only showing "what=0"

如何更改消息的值,这样我可以做基于消息不同的东西?

How do I change the values of Message so that I can do different things based on the message?

谢谢!

推荐答案

您必须从消息中的数据(如捆绑,然后为INT)已发送你的处理程序:

You must get the data from the Message (as Bundle then as int) you have sent in the handler you do:

Handler seconds=new Handler() { 
    @Override 
    public void handleMessage(Message msg) { 
      int sentInt = msg.getData().getInt("what");
      bar.incrementProgressBy(5); 
       tView1.setText("r:"+Integer.toString(sentInt));
    } 
  }; 

这篇关于Android的处理器消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆