Android Messaging Handler

I have very simple code for 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'm trying to change the " what " value in the message, so I can do different things based on the message, but according to " tView1.setText("r:"+msg) " the value "" does not change to 5 :( it only shows " what=0 "

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

Thanks!

+6
source share
2 answers

You should get the data from the message (like Bundle then as int) that you sent in the handler you make:

 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)); } }; 
+7
source

You need to extract the message in the same way as you received 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 ...

PS I ignored the null check for simplicity, but you have to check if data null ...

+2
source

Source: https://habr.com/ru/post/893432/


All Articles