【发布时间】:2019-05-11 12:42:12
【问题描述】:
我目前正在通过蓝牙将一个对象(购物)从一个用户发送到另一个用户。
当我从我的服务器电话点击“发送”按钮时,购物对象已正确发送,我通过Log.d(StringNameOfShopping)在我的终端上打印它
但我只能发送bytes[] 数组,将其转换为 int 字节然后创建一个new String(buffer[], offset, bytes)
那么有没有一种方法可以从字符串(例如我的购物对象参考:Shopping@bd429a9)转换为购物对象?
这是我收听输入和输出的方法。
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
String text = new String(bytes, Charset.defaultCharset());
Log.d(TAG, "write: Writing to outputstream: " + text);
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
这是我的序列化/反序列化方法(但我应该把它们放在哪里?在我的 MainActivity 或购物类中?或蓝牙类?
public byte[] serialize(Shopping shopping) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(shopping);
return b.toByteArray();
}
//AbstractMessage was actually the message type I used, but feel free to choose your own type
public static Shopping deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return (Shopping) o.readObject();
}
【问题讨论】:
标签: java android casting bluetooth