在 Android 中通过蓝牙对象 sending/receiving

Object sending/receiving via Bluetooth in Android

我正在尝试使用 ObjectOutputStream 将对象发送到另一个设备 运行 android。我不断收到 ClassNotFoundException。

我的 class 实现了 Serializable。我还没有尝试使用 Parcelable 实现序列化以通过蓝牙将对象发送到另一台设备。有人试过吗? 请问你的意见?谢谢

可序列化或可打包是实现我的目的的正确方法吗?

//mmSocket is the socket i got from a bluetooth connection
//this is for sending an object
public void writeSerialized(){
        Object contact = new Contact("Allen", "Patterson", "256-369-241");
        try {
            ObjectOutputStream oos = new  ObjectOutputStream(mmSocket.getOutputStream());
            oos.writeObject(contact);
            oos.close();
        }catch(Exception e){
            Log.e(TAG, "Error ObjectOutputStream: "+e.getLocalizedMessage());
        }
    }

//mmInputStream是我从socket中得到的Stream。 这是给接收端的

 public void run() {
        // Keep listening to the InputStream while connected
        while (true) {

            try {

                ObjectInputStream ois = new ObjectInputStream(mmInStream);
                Object contact = ois.readObject();
                Log.i(TAG,"Contact class: "+contact);

            } catch (IOException | ClassNotFoundException e) {
                Log.i("ERROR", "E:"+e.getLocalizedMessage());
            }
        }
    }

//我试图在另一个尺寸上发送和接收的对象

public class Contact implements Serializable{

static final long serialVersionUID = 123456789123456789L;

private String id;
private String name;
private String phoneNumber;

public Contact(){}

public Contact(String id, String name, String phoneNumber) {
    this.id = id;
    this.name = name;
    this.phoneNumber = phoneNumber;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhoneNumber() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

}

解决方案是让 Serializable 在应用程序的两侧以相同的包名实现 class。例如 com.shared.models 并为可序列化 class 提供相同的 SerialVersionUID。帮我解决了