【问题标题】:Object sending/receiving via Bluetooth in Android在 Android 中通过蓝牙发送/接收对象
【发布时间】:2015-11-24 05:21:09
【问题描述】:

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

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

serializable 或 parcelable 是实现我的目的的正确方法吗?

【问题讨论】:

  • 我们可以看看一些代码吗?
  • 我在那里添加了一些代码。你能看到代码中的任何低效率或任何东西吗?

标签: java android bluetooth communication serializable


【解决方案1】:
//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 实现类在同一个包名中。例如 com.shared.models 并为可序列化类提供相同的 SerialVersionUID。为我解决了这个问题

【讨论】:

    猜你喜欢
    • 2015-04-21
    • 2013-08-02
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多