[英]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.