简体   繁体   English

在Android中通过蓝牙发送/接收对象

[英]Object sending/receiving via Bluetooth in Android

I am trying to send an object to another device running android using ObjectOutputStream. 我正在尝试使用ObjectOutputStream将对象发送到运行android的另一设备。 I keep getting ClassNotFoundException. 我不断收到ClassNotFoundException。

My class implements Serializable. 我的课实现了Serializable。 I haven't tried implementing serialization using Parcelable to send objects via Bluetooth to another device. 我没有尝试使用Parcelable实现序列化以通过蓝牙将对象发送到另一台设备。 Has anyone tried that? 有人尝试过吗? Your opinions please? 请发表您的意见? thank you 谢谢

Is serializable or parcelable the right way to go about my purpose? 可序列化或可打包是实现我的目标的正确方法吗?

//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 is Stream I got from socket. // mmInputStream是我从套接字获取的Stream。 This is for receiving side 这是给接收方的

 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());
            }
        }
    }

//the object I am trying to send out and receive on the other size //我尝试发送和接收的对象的大小是其他大小

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;
}

} }

The solution is to have the Serializable implementing class on both sides of the application in the same package name. 解决方案是在应用程序的两侧都使用相同的包名称来实现Serializable实现类。 For example com.shared.models and give the serializable class the same SerialVersionUID. 例如com.shared.models并为可序列化类提供相同的SerialVersionUID。 that solved it for me 为我解决了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM