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...
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.
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.
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.
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 :)
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With