Android 通过 Intent 将对象发送到服务而无需绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2251985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending an object to a service through Intent without binding
提问by jax
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...
是否可以通过 Intent 将对象发送到 Android 服务而不实际绑定到服务?或者也许是服务访问对象的另一种方式......
回答by Binh Tran
You can call startService(Intent) like this:
您可以像这样调用 startService(Intent):
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)
你要发送的对象必须实现Parcelable(你可以参考这个Percelable 指南)
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:
使用服务,在 api 级别 5 及更高级别的 onStart() 或 onStartCommand() 方法中,您可以获得对象:
MyObject obj = intent.getParcelableExtra("object");
That's all :)
就这样 :)
回答by Khaled Annajar
If you don't want to implement Parcelableand your object is serializable
如果您不想实现Parcelable并且您的对象是可序列化的
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 :)
对我来说很好用试试吧。但对象必须是可序列化的:)
回答by Timo Reimann
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.
就像 Bino 所说的,如果你想通过一个意图将它传递给一个服务,你需要让你的自定义对象实现 Parcelable 接口。这将使对象在 Android IPC 意义上“可序列化”,以便您可以将它们传递给 Intent 的对象 putExtra(String, Parcelable) 调用。
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.
对于简单的原始类型,已经有很多 setExtra(String, primitive type) 方法。但是,据我了解,这不是您的选择,这就是您应该选择包裹的原因。