0

As the below, I created 2 inner classes which both extend Handler. I have read the code in Android source files, found Handler.sendEmptyMessage() only enqueued the message in the Looper's message queue.

public class MainActivity extends Activity{
    private Handler handler = new Handler(Looper.getMainLooper()){
        public void handleMessage(Message msg){
            //handle method1
        }
    }
    ......
}

public class MyService extends Service{
    private Handler handler = new Handler(Looper.getMainLooper());

    public void test(){
        handler.sendEmptyMessage(0x00);
    }
    ......
}

So, I am confusing about why the first Handler in MainActivity cannot handle the message from the second Handler in MyService when the constructed with the same looper?

r5d
  • 579
  • 5
  • 24
Tommy
  • 301
  • 2
  • 16
  • 1
    If you want to send message from your service to your activity, this is not the right way to do it. You can check this: http://stackoverflow.com/questions/4300291/example-communication-between-activity-and-service-using-messaging for more information. – Rotem Jul 19 '15 at 06:44
  • @Rotem Could you tell me what will happen if I have multiple handlers which associated with the same looper? – Tommy Jul 19 '15 at 06:47
  • 1
    You can't communicate between handlers, each handler have his own message queue - as answered here: http://stackoverflow.com/questions/15538270/handlers-initialized-with-looper-getmainlooper-does-not-respond-to-message-cal?answertab=votes#tab-top – Rotem Jul 19 '15 at 06:53

1 Answers1

0

You can't communicate between handlers, each handler have his own message queue - as answered here:

Handlers initialized with Looper.getMainLooper() does not respond to message callbacks

Community
  • 1
  • 1
Rotem
  • 2,306
  • 3
  • 26
  • 44
  • [android.os.handler](http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.0_r1/android/os/Handler.java#Handler.%3Cinit%3E%28android.os.Handler.Callback%2Cboolean%29) I can't make sure that every handler has **its own message queue**.In the source code, **mQueue = mLooper.mQueue**. – Tommy Jul 19 '15 at 07:41
  • It's not his own, it's the thread's messaging queue and every handler is associated with a single tread. I understand what you are trying to do but it doesn't suppose to work like this. – Rotem Jul 19 '15 at 07:48