Android 的蓝牙聊天示例对于学习如何在手机之间传递字符串非常有用 - 是否可以使用相同的代码在手机之间传递对象?我在两部手机中定义了相同的类,我只想将一个类的实例从一部手机传递到另一部手机。有可用的示例代码吗?我尝试使用序列化并用 objectoutputstream 和 objectinputstream 替换聊天示例中的输出流和输入流,但它似乎不起作用
我发现处理这个问题的最佳方法如下:
- 我将我的对象设置为实现我想要发送的可序列化。
-
我设置了以下代码来管理消息:
public byte[] serialize() throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(this);
return b.toByteArray();
}
//AbstractMessage was actually the message type I used, but feel free to choose your own type
public static AbstractMessage deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return (AbstractMessage) o.readObject();
-
我更改了写入语句以接受可序列化,然后进行最终写入:
/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(AbstractMessage buffer) {
try {
Log.v(TAG,"Writing \""+(buffer.serialize())+"\"");
mmOutStream.write(buffer.serialize());
// Share the sent message back to the UI Activity
mHandler.obtainMessage(AbstractMessageManager.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)