Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending an object to a service through Intent without binding

Tags:

android

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...

like image 772
jax Avatar asked Feb 12 '10 13:02

jax


People also ask

Can I send an object in intent Android?

One way to pass objects in Intents is for the object's class to implement Serializable. This interface doesn't require you to implement any methods; simply adding implements Serializable should be enough. To get the object back from the Intent, just call intent.

How do you share data between activity and service?

Primitive Data Types To share primitive data between Activities/Services in an application, use Intent. putExtras(). For passing primitive data that needs to persist use the Preferences storage mechanism. The android.

How pass data from activity to services in Android?

Explanation. Using putExtra() method, we can send the data. While using it, we need to call setResult() method in services. We can also store data in a common database and access it on services as well as in Activity.


2 Answers

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 :)

like image 149
Binh Tran Avatar answered Oct 27 '22 18:10

Binh Tran


If you don't want to implement Parcelable and your object is serializable

use this

In the sender Activiy

Intent intent = new Intent(activity, MyActivity.class);

Bundle bundle = new Bundle();
bundle.putSerializable("my object", myObject);

intent.putExtras(bundle);

startActivity(intent);

In the receiver:

myObject = (MyObject) getIntent().getExtras().getSerializable("my object");

Works fine for me try it. But the object must be serializable :)

like image 43
Khaled Annajar Avatar answered Oct 27 '22 20:10

Khaled Annajar