0

This topic has been discussed many times so far, but still haven't managed got it working.

My MainActivity has a property called Handler mHandlerUi; which is initialized in its constructor

mHandlerUi = new Handler() {
            @Override
            public void handleMessage(Message msg){
                onMessageArrive(msg);
            }
        };

Later on in the code, In another class, during construction time i initialize another Handler property

mHandlerToUi = new Handler(Looper.getMainLooper());

So during the thread's life time, the following code snippet is executed X times.

    Message msg = mHandlerToUi.obtainMessage();
    msg.what = ConstMessages.MSG_NEW_GPS_POINT;
    msg.setData(bundleContet);

    mHandlerToUi.sendMessage(msg);

Unfortunately the message never arrives the MainActivity's Looper, Both threads uses the same UI's looper,

What am i missing over here?

igal k
  • 1,883
  • 2
  • 28
  • 57

2 Answers2

1

If I understand you correctly, you have initiated two handlers and you want to pass the message from one to another?

Perhaps you should pass the handler to the second class instead. So in your MainActivity you have

mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message inputMessage) {
            onMessageArrive(msg);
        }
    }

and pass this mHandler to your second class via constructor or setter method.

qichuan
  • 1,110
  • 7
  • 8
  • This exactly what I'm trying to do, but how come i need to share Handler's reference among the classes, and not its looper? Is there a way to achieve same effect is if i would use DuplicateHandle(c language) – igal k Aug 24 '17 at 06:41
  • Kevinrob has answered your question, what stops you from passing the handler reference? – qichuan Aug 24 '17 at 06:56
1

Each Handler handle its messages. The Looper is used for running a Handler on a specific Thread.

If you create two Handler, there will not communicate. There will only share the same Looper that run on a Thread.

You can find good answers on What is the relationship between Looper, Handler and MessageQueue in Android?

Kevin Robatel
  • 8,025
  • 3
  • 44
  • 57
  • So Looper is just the queue management among other instances, but communication itself is done by the Handler? – igal k Aug 24 '17 at 07:05
  • 1
    @igalk read [this](https://blog.mindorks.com/android-core-looper-handler-and-handlerthread-bd54d69fe91a) – pskink Aug 24 '17 at 07:14