Friday, 23 October 2015

use android handler to send message

First this will not make your code loose couple if you do wrongly. because you need to use the same handler to send massage and handle massage.

You may ask why i should use handler to send message to notify another class or activity or services.... to do something? I can call them directly. the reason is 1. it is not loose couple. 2. most of time you can't do this, especially for activity, only the activity can change UI otherwise you will get error (only the original thread can touch the UI structure ).

I will use an example from one of my blog:

I was trying to change menus from other places, then I got the error which i mentioned above.

my solution is :

  1. // in my activity
  2. private android.os.Handler handler = new android.os.Handler() {
  3. @Override
  4. public void handleMessage(Message msg) {
  5. switch (msg.what){
  6. case 1000:
  7. change menu....
  8. break;
  9. case 1001:
  10. change menu....
  11. break;
  12. super.handleMessage(msg);
  13. }
  14. };

  15. // in the place i want to control my menus
  16. new Thread() {
  17. @Override
  18. public void run() {
  19. handler.sendEmptyMessage(1000);
  20. }
  21. }.start();

No comments:

Post a comment