Reprint please specify from: http://blog.csdn.net/icyfox_bupt/article/details/25487125
Recently in the laboratory to do projects, using the Android Bluetooth development, there are a lot of pits. So I still hope to remember these things to share with you, do not go my way.
First of all, I am developing mobile phone with Bluetooth smart device (Bluetooth sphygmomanometer, blood glucose meter, bracelet, etc.) device docking app. In other words, there is nothing to operate on the device side, the mobile phone is responsible for initiating data transmission.
- Bluetooth connection, do not need
pairing
because I was misled by the idea of using Bluetooth, we always thought that using Bluetooth was a pairing process. That's not really the case. After searching the device, go directly to connect
device instead of pairing, currently in my here is no problem, after searching the device, you can directly use the code to connect:
final String spp_uuid = " 00001101-0000-1000-8000-00805F9B34FB "; UUID uuid = uuid.fromstring (spp_uuid); Bluetoothsocket socket ; socket = Device.createinsecurerfcommsockettoservicerecord (UUID); Adapter.canceldiscovery (); socket . connect (); The UUID here is a more useful one, the device can be identified.
startDiscovey
It is possible to start failure
There are two steps in the general procedure:开启蓝牙
、开始寻找设备
。 The code I wrote earlier is that the user presses the button to perform these two steps in a direct order, resulting in a recurring search failure. Take a closer look at the API and discoveradapter.startDiscovery()
The function has a Boolean return value, which means that it returns false if it fails to start. This explains why the startup failed: Sequential execution开启蓝牙
-寻找设备
, but since Bluetooth is not fully open, it starts looking for devices, which leads to a search for failure. So in the end I changed the code so that the problem solved:
adapter = Bluetoothadapter.getdefaultadapter ();if(Adapter = =NULL) {//device does not support Bluetooth}//Turn on Bluetoothif(!adapter.isenabled ()) {adapter.enable (); Adapter.canceldiscovery ();}//Search for Bluetooth devices, Android will send the found device in broadcast form while(!adapter.startdiscovery ()) {LOG.E ("BlueTooth","Attempt Failed");Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {E.printstacktrace (); }}
Receive Data conversions
Using the socket.getInputStream
received data is a byte stream, such data can not be analyzed. And because generally the factory gives the agreement is similar to "FA D0" such as hex data, so many cases need a byte to hexadecimal string function:
Public StaticStringBytestohex(byte[] bytes) {Char[] Hexchars =New Char[Bytes.length *2]; for(intj =0; J < Bytes.length; J + +) {intv = bytes[j] &0xFF; HEXCHARS[J *2] = Hexarray[v >>>4]; HEXCHARS[J *2+1] = hexarray[v &0x0F];}return NewString (hexchars);}
-