Is mHandler.obtainMessage supposed to fire handleMessage(Message msg)

842 views Asked by At

Second question of the day! (Sorry, Newbie)

I'm trying to create a separate thread, and in that thread I need to be able to send information back to the UI thread. For this, I went ahead and created a new Handler Class:

private static class nHandler extends Handler{
    private final WeakReference<MainActivity> mTarget;
    public nHandler(MainActivity context){
        mTarget = new WeakReference<MainActivity>((MainActivity) context);
    }

    @Override
    public void handleMessage(Message msg){ Log.d("Something", "It got here")}
    }

In my main activity class I have a private static nHandler mHandler; I then created a handler in my onCreate() using mHandler = new nHandler(this);

When I create my other thread, and it runs I create a handler object and set it to the one I passed in the constructor. In this other class I then have a function:

private synchronized void setState(int state){
    //lets add some logging
    mState = state;
    //Give the handler something so the Main Activity Updates
    mHandler.obtainMessage(MainActivity.HANDLER_CHANGE_SERVER_STATUS, state, -1);
}

But in the Log I don't see my log come up. I may not completely understand how handlers are supposed to work, so if you think that is the case can you help me understand them and get it working right?

Thanks!

2

There are 2 answers

0
Linux4Hope On

Ok Guys.....

Well I figured it out.

Anytime you do

mHandler.obtainMessage() make sure you include .sendToTarget();

So in the end it looked like:

mHandler.obtainMessage(MainActivity.HANDLER_CHANGE_SERVER_STATUS, state, -1).sendToTarget();

I'm leaving this question up in case someone else Google's for it

0
Ramesh Yankati On

You have to send the obtained message.

 mHandler.sendMessage( mHandler.obtainMessage(MainActivity.HANDLER_CHANGE_SERVER_STATUS, state, -1));