繁体   English   中英

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

[英]Object sending/receiving via Bluetooth in Android

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

我的课实现了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是我从套接字获取的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实现类。 例如com.shared.models并为可序列化类提供相同的SerialVersionUID。 为我解决了

暂无
暂无

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

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