Send Object from Service to Activity (Can't marshal non-Parcelable)

cmg_george picture cmg_george · Jul 6, 2011 · Viewed 9.6k times · Source

I'm trying to send data from my activity to a service and receive some information back, but i'm getting:

java.lang.RuntimeException: Can't marshal non-Parcelable objects across processes.

The code from activity looks like this:

Message msg = Message.obtain(null, 1);
    msg.obj=1;
    msg.replyTo=new Messenger(new PlanRequestIncomingHandler());
    try {
        msgService.send(msg);
    } catch (RemoteException e) {
        Log.i(tag, "Can not send msg to service");
        e.printStackTrace();
    }

When I set msg.obj = something I get java.lang.RuntimeException, can somebody help me?

Answer

Mohanraj Balasubramaniam picture Mohanraj Balasubramaniam · Jan 29, 2015

You can pass Parcelable type objects via Messenger. Or else if you want to pass primitive data types use Bundle wrapper as below.

In Service End:

//Create a bundle object and put your data in it
Bundle bundle = new Bundle();
bundle.putInt("key", 1);

Message msg = Message.obtain(null, 123);
msg.obj = bundle;
msg.replyTo = new Messenger(new PlanRequestIncomingHandler());
try {
    msgService.send(msg);
} catch (RemoteException e) {
    Log.i(tag, "Can't send msg to service");
    e.printStackTrace();
}

In Activity End:

switch(msg.what) {
    case 123:
        if(msg.obj != null) {
            Bundle bundle = (Bundle) msg.obj;
            System.out.println("Got integer "+ bundle.getInt("key"));
        }
    break;
}

cheers :-)