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!
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));
}
};
You need to extract the message in the same way you got it:
public void handleMessage(Message msg) {
bar.incrementProgressBy(5);
Bundle data = msg.getData();
tView1.setText("r:"+data.getInt("what"));
}
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With