如何通过意图将对象发送给Android中的其他Activity?

问题描述:

我正在开发Android。我尝试将蓝牙对象发送给另一个活动。如何通过意图将对象发送给Android中的其他Activity?

代码

BluetoothSocket btSocket; 

Intent i = new Intent(ActivityA.this, ActivityB.class); 
i.putExtra(EXTRA_BT_SOCKET,btSocket); 
startActivity(i); 

但它似乎没有工作,它显示了如下错误:

无法解析法“putExtra(java.lang.String中, 机器人。 bluetooth.BluetoothSocket)

如何通过意向发送蓝牙对象到另一个Act Android中的ivity?

在此先感谢。

+1

它显示了什么错误? – Kiya

+1

@Kiya it show无法解析方法'putExtra(java.lang.String,android.bluetooth.BluetoothSocket)。 – Wun

+0

据我所知,你只能传递可以实现Parcelable或Serializable接口的对象,所以我也被卡住了,所以我做的事情是让对象成为静态的,并从其他类访问它:public static BluetoothSocket btSocket;当我去其他活动时,我只是做了BluetoothSocket copyOfBtSocket = ActivityA.btSocket; – Pulkit

使用以下方法来发送和检索对象:

//要传递: intent.putExtra( “MyClass的”,OBJ);

// To retrieve object in second Activity 
getIntent().getSerializableExtra("MyClass"); 
+0

如果您正在尝试此操作,请确保您投射它@ i.putExtra(DeviceListActivity.EXTRA_ADDRESS,(Serializable)address); – Pulkit

+0

我试过了,它会在i.putExtra(“MyClass”,(Serializable)btSocket)上显示'putExtra(java.lang.String,android.bluetooth.BluetoothSocket); – Wun

+0

检索时使用getparceable()。 –

使用一个辅助类

public class BluetoothSocketHelper implements Serializable { 

    public BluetoothSocket btSocket; 

    //Constructor + getter/setters 
} 

从ActivityA发送:

BluetoothSocketHelper bluetoothSocketHelper; 

Intent i = new Intent(ActivityA.this, ActivityB.class); 
i.putExtra(DeviceListActivity.EXTRA_ADDRESS, address); 
i.putExtra(EXTRA_BT_SOCKET, bluetoothSocketHelper); 
startActivity(i); 

然后在ActivityB:

private BluetoothSocket btSocket; 

if(getIntent().getExtras()!=null){ 
    bluetoothSocketHelper = (BluetoothSocketHelper) getIntent().getSerializableExtra(EXTRA_BT_SOCKET); 
    btSocket = (BluetoothSocket) bluetoothSocketHelper.getBluetoothSocket(); 
} 
+0

只有声明它实现了Serializable'',才能创建一个'BluetoothSocket'序列化。这是一个插座,它是连接到蓝牙设备的插座。当你序列化和反序列化一些东西时,它会复制这个对象。你不能像这样复制一个套接字。你不能以这种方式将一个套接字对象放入一个'Bundle'或一个'Intent'' extra“中。 –

,你可以把它当作一个包通过的意图

Bundle bundle = new Bundle(); 
bundle.putParcelable("yourObject key name", YOUR_OBJECT); //make YOUR_OBJECT implement parcelable 
Intent intents = new Intent(ActivityA.this, ActivityB.class); 
intents.putExtra(Constants.BUNDLE_DATA, bundle); 
startActivity(intents); 

在recieving结束(ActivityB.class)

if (intent != null && intent.hasExtra(Constants.BUNDLE_DATA)) { 
     Bundle bundle = intent.getBundleExtra(Constants.BUNDLE_DATA); 
     if (bundle != null && bundle.containsKey(yourObject key name)) { 
      Object yourObject = bundle.getParcelable(yourObject keyname); 
    } 
+0

OP正试图传递一个'BluetoothSocket'。这个类没有实现'Parcelable'或'Serializable',所以它不能放在'Bundle'中。 –

你不能把一个BluetoothSocket例如在Bundle或者把它作为一个Intent “额外” 这样的。这将需要序列化和反序列化对象,这会制作对象的副本。你不能复制这样的套接字。你想要做的就是在多个活动之间共享对象。最简单的方法是将对象的引用放在某个变量的public static变量中,并从需要访问的所有活动中使用它。