Sending An Object To A Service Through Intent Without Binding
Solution 1:
You can call startService(Intent) like this:
MyObjectobj=newMyObject();
Intentintent=newIntent(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)
classMyObjectextendsObjectimplementsParcelable {
@OverridepublicintdescribeContents() {
// TODO Auto-generated method stubreturn0;
}
@OverridepublicvoidwriteToParcel(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:
MyObjectobj= intent.getParcelableExtra("object");
That's all :)
Solution 2:
If you don't want to implement Parcelable and your object is serializable
use this
In the sender Activiy
Intentintent=newIntent(activity, MyActivity.class);
Bundlebundle=newBundle();
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 :)
Solution 3:
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.
Post a Comment for "Sending An Object To A Service Through Intent Without Binding"