I recently worked on a project in the lab and used Android Bluetooth development. There are many pitfalls in this project, so I still hope to write down these things and share them with you, so I don't want to go on my own.
Let's talk about the background. I am an APP that develops mobile phones and smart devices with Bluetooth (such as Bluetooth sphygmomanometer, blood glucose meter, and wristband. That is to say, there is no operation on the device, and the mobile phone is responsible for initiating data transmission.
- Bluetooth connection not required
Pairing
Being misled by the idea of using Bluetooth, I always thought that using Bluetooth requires a pairing process. This is not the case. After searching for the device, go directlyconnect
The device does not need to be paired. At present, there is no problem here. After searching for the device, you can directly use the following code to connect:
Final String SPP_UUID = 20171101-0000-1000-8000-00805f9b34fb; UUID uuid = UUID. fromString (SPP_UUID); effecthsocket socket; socket = device. createInsecureRfcommSocketToServiceRecord (uuid); adapter. cancelDiscovery (); socket. connect (); the UUID here is a good one and can be identified by devices.
startDiscovey
Startup may fail.
The general program has two steps:Enable Bluetooth
,Start searching for devices
. The code I wrote previously is that the user directly executes these two steps by pressing the button, resulting in frequent search failures. After carefully reading the API, we found thatadapter.startDiscovery()
A function returns a boolean value, that is, if the startup fails, false is returned. This explains why the startup failed: sequential executionEnable Bluetooth
-Find a device
But because the Bluetooth has not been fully turned on, start to find the device, resulting in a failure to find. So I finally changed the code to this, and the problem was solved:
Adapter = descrithadapter. getdefaadapter adapter (); if (adapter = null) {// The device does not support Bluetooth} // turn on the Bluetooth if (! Adapter. isEnabled () {adapter. enable (); adapter. cancelDiscovery ();} // find a bluetooth device. android broadcasts the device to the while (! Adapter. startDiscovery () {Log. e (BlueTooth, failed); try {Thread. sleep (100);} catch (InterruptedException e) {e. printStackTrace ();}}
Receive Data Conversion
Usesocket.getInputStream
The received data is a byte stream, which cannot be analyzed. Generally, the protocol provided by the manufacturer is similar to the hexadecimal data of FA 22 89 D0. Therefore, in many cases, a byte function is required to convert the hexadecimal String:
public static String bytesToHex(byte[] bytes) {char[] hexChars = new char[bytes.length * 2];for ( int j = 0; j < bytes.length; j++ ) { int v = bytes[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F];}return new String(hexChars);}