Sending Data via Bluetooth

拟墨画扇 提交于 2019-12-03 10:17:31

问题


I'm a little confused about how to send data over a Bluetooth connection. In the Android API documentation, from the Bluetooth Chat example, the class BluetoothChat.java constructs a Handler object. Within there is a switch statement, and a MESSAGE_WRITE case. Do I need to implement similar code to send Strings over Bluetooth? A case statement for each String I want to send? In particular I want to send (name,value) pairs so I know what is sent and what it's value is. How do I implement this? If, following the example, I call BluetoothChatService.write(String.getBytes()) a bunch of times to send...? Then how would I know which strings are associated with which names? Please help.


回答1:


I'm using Google's Protocol Buffers to send structured data over bluetooth connections in my Android app. protobuf takes care of figuring out how to serialize the message for you so that you only have to send a byte value (length of the message) and then the serialized message; the library takes care of unserializing the message on the other end and populating the fields of a custom object. Definitely take a look at it; it made the writing of a custom bluetooth socket protocol quite easy.




回答2:


Serialize pairs to any of formats which allows byte representation. Such as XML or JSON. Or even your custom format, it wouldn't be difficult for pairs of strings. And then send it.




回答3:


For simple pairs of strings (Such as names), you could simply use some character to define when the first string stops, and the next begins.

For example, I use a format such as this to send a set of 3 strings from one device to another:

String toSend = partOne + ":" + partTwo + ":" + partThree;

On the other device, to get the strings you sent, use the String.split() method like so:

String parts[] = received.split(":",3);

The 2nd parameter is a limit to how many times to split. In this example, there are 3 strings, so split 3 times max.

The downside to doing this is that you need to use characters that will never be in all but the last string.

In my application, I used this method to send data about text messages, and the first 2 parts are the phone number and timestamp, so there can never be a : in it. For names, a newline would probably work.

If your going to send more complex data, definitely use something like Protocol Buffers.



来源:https://stackoverflow.com/questions/6609373/sending-data-via-bluetooth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!