How to pass any object from activity to service?

2019-04-14 15:50发布

I want to pass object of "BluetoothDevice" class from an activity to service. I am getting syntaxes for passing Strings or any primitive types but not passing objects. Please Help. Thanx in advance.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-04-14 16:42

you should create a class containing your data to be passed and extend that from Serializable or Parcelable and then you can put an object of that class as an Extra to your Intent and use it in your Service

EDIT : as rom4ek mentioned, BluetoothDevice is already implements Parcelable and all you have to do is :

Bundle b = new Bundle();
b.putParcelable("data", yourBluetoothDeviceObject);
yourIntent.putExtra(b);

and for retrieving data :

Bundle b = yourIntent.getExtra();
BluetoothDevice device = (BluetoothDevice) b.getParcelable("data");
查看更多
Explosion°爆炸
3楼-- · 2019-04-14 16:42

You can make your complex object implement Serializable or Parcelable and then you can pass it to Service using putExtra(String name, Serializable value) or putExtra(String name, Parcelable value)

查看更多
登录 后发表回答