tags:

views:

146

answers:

2

Is is possible to send an object to an Android Service through an Intent without actually binding to the service? Or maybe another way for the Service to access Objects...

+3  A: 

You can call startService(Intent) like this:

MyObject obj = new MyObject();
Intent intent = new Intent(this, MyService.class);
intent.putExtra("object", obj);
startService(intent);

The object you want to send must implement Parcelable (you can refer to this Percelable guide)

class MyObject extends Object implements Parcelable {

    @Override
    public int describeContents() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        // TODO Auto-generated method stub

    }

}

And with the Service, in the method onStart() or onStartCommand() for api level 5 and newer, you can get the object:

MyObject obj = intent.getParcelableExtra("object");

That's all :)

Bino
How do I send more than a single data value to the Parcel? I have two Strings I need to send.
jax
intent.putExtra("my.first.string", "something");intent.putExtra("my.second.string", "something else");
hackbod
This is still not working for me. I have done all of the above but am still having problems. How am I meant to pass the entire state of the object over through Parcelable? I know I can send basic types like String and Arrays but by object contains more complex classes than just these.
jax
A: 

Like Bino said, you need to have your custom object implement the Parcelable interface if you want to pass it to a service via an intent. This will make the object "serializable" in an Android IPC-wise sense so that you can pass them to an Intent's object putExtra(String, Parcelable) call.

For simple primitive types, there's already a bunch of setExtra(String, primitive type) methods. As I understand you, however, this is not an option for you which is why you should go for a Parcel.

Timo