Android的 - 通过蓝牙传递对象 [英] Android - Pass object via bluetooth
问题描述
蓝牙聊天的例子为Android是非常有用的,学习如何通过手机之间的字符串 - 是否有可能使用相同的code通过电话之间的对象?我在这两款手机中定义相同的类,我只是想从一个电话中传递一个类的实例到另一个。有什么样code可用?我尝试使用序列化和更换的OutputStream和InputStream中与ObjectOutputStream中和ObjectInputStream的聊天的例子,但它似乎没有工作
The Bluetooth chat example for Android is very useful to learn how to pass strings between phones - is it possible to use the same code to pass objects between phones? I have the same classes defined in both phones, I just want to pass the instance of one class from one phone to another. Is there any sample code available? I tried using serialization and replacing outputstream and inputstream in the chat example with objectoutputstream and objectinputstream but it didn't seem to work
推荐答案
我发现来处理,这是下面的最佳方式:
The best way I found to handle this was the following:
- 在我建立了我的对象为实现Serializable,我想送。
-
我设置了以下code管理消息:
- I set up my objects as implementing Serializable that I wanted to send.
I set up the following code to manage the messages:
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();
我改了写语句接受一个序列化,然后再作出最后的写:
I changed the write statements to accept a Serializable, and then make the final write:
/**
* 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);
}
}
这篇关于Android的 - 通过蓝牙传递对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!