Put an object in Handler message

Tsimmi picture Tsimmi · Jun 9, 2010 · Viewed 37.7k times · Source

I need to download an image from the internet, in a different thread,
and then send that image object in the handler message, to the UI thread.

I already have this:

...
Message msg = Message.obtain();

Bundle b = new Bundle();
b.putParcelable("MyObject", (Parcelable) object);
msg.setData(b);

handler.sendMessage(msg);

And when I receive this message, I want to extract the object:

...
public void handleMessage(Message msg) {
    super.handleMessage(msg);

    MyObject objectRcvd = (MyObject) msg.getData().getParcelable("IpTile");
    addToCache(ipTile);
    mapView.invalidate();
}

But this is giving me:

...java.lang.ClassCastException...

Can anyone help?

And by the way, is this the most efficient way
to pass an object to the UI Thread?

Thank you all!

Answer

Caspar Harmer picture Caspar Harmer · Jun 29, 2011

I know I'm late to the party, but there is an easier way if you are using the service within a single process. You can attach any arbitrary Object to your Message using this line:

msg.obj = new CustomObject() // or whatever object you like

This is working well for me in my current projects.
Oh, and I'm moving away from using AsyncTask objects, as I believe they increase code coupling too much.