Android,消息处理程序
我有一些非常简单的代码与处理程序有关:
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
}
}
});
正如您在上面看到的,我正在尝试更改消息中“what
”的值,这样我就可以根据消息,但根据“tView1.setText("r:"+msg)
”,“what
”的值不会更改为 5 :(
它只显示“what=0
”
如何更改 Message 的值,以便我可以根据消息执行不同的操作?
谢谢!
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);
}
};
And my thread:
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
}
}
});
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?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须从您在处理程序中发送的消息(作为 Bundle,然后作为 int)获取数据:
You must get the data from the Message (as Bundle then as int) you have sent in the handler you do:
您需要以与获取消息相同的方式提取消息:
抱歉,在之前的答案中没有澄清这一点...
PS 为了简单起见,我忽略了对 null 的检查,但您应该检查
data
是否为 null ...You need to extract the message in the same way you got it:
Sorry for not clarifying that in the previous answer...
P.S. I ignored checking for null for simplicity, but you should check if
data
is null...