brief introduction
Since the Android BLE library has been open source for some time, more and more friends have asked all kinds of strange questions about BLE. Here, I want to share with you some of my views and solutions on Android BLE Bluetooth, so as to avoid the new friends stepping on the pit again.
Digression
Many people have asked me this question. Why are there no problems with other mobile phones? Some Huawei mobile phones are always connected unstable, often connected very slowly, and often disconnected. Indeed, I would like to emphasize that some Huawei mobile phones are prone to such problems. Sometimes the software and hardware are uncertain, and we often receive customer complaints. There is no complete solution to the problem of Huawei mobile phone connection stability. We can only rely on the optimization of App and hardware. We don't want to throw the pot to Huawei. We don't dare to ask what the reason is, Moreover, our company has specially tested various Android versions of mobile phones, including Bluetooth transmission rate. Finally, it is found that the speed of Huawei P20 is several times worse than that of Xiaomi 8. It is reasonable that P20 mobile phones are not cheap. Why can't mobile phone Bluetooth chips be better?
Problem collection
1, Scan problem
1. Device not scanned
First determine whether the following items are met: 1,Is Bluetooth on 2,Are Bluetooth related permissions authorized(6.0 Above location permissions) 3,7.0 Many of the above mobile phones need to be opened manually GPS
2. Sometimes the scanning is normal at the beginning, and the device cannot be scanned after a period of time?
reason: Many of the problems are Android7.0 The above mobile phones, why? because Google To prevent Android7 Medium BLE Scan abuse, thus making some restrictions, that is, don't use it at 30 s Internal Bluetooth scanning Repeat opening-Shut down more than 5 times. Recommendations: Set scan cycle>6s, After the user clicks scan, do not repeat the scan. You can make a flag bit to check whether the scan is in progress. If If you are scanning, you will not repeat the scanning action.
3. Why do some mobile phones go back to the background and can't scan the device
Android8.0 After returning to the background information screen, in order to ensure power saving and other reasons, if it is not set ScanFilters By default, the device cannot be scanned, So the solution is to set as follows: mScannerSetting = new ScanSettings.Builder() //Set the scan mode to low power consumption when going back to the background .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER) .build(); mFilters.add(new ScanFilter.Builder() //Filter and scan the main service of Bluetooth devices .setServiceUuid(ParcelUuid.fromString("0000ffff-0000-1000-8000-00805f9bfffb")) .build()); mScanner.startScan(mFilters, mScannerSetting, mScannerCallback);
In the rest screen state, the Bluetooth scans the log. Because the scanning cycle is 12s, the time stamp interval printed is 12s. The log here is the system log.
Translation: Start Bluetooth scan. The scan results will be passed through the callback. For unfiltered scans, the scan is stopped and turned off on the screen to save time Electricity. When you open the screen again, the scan will resume. To avoid this, scan the file using the appropriate scan filter.
2, Connection problem
1. Why is the connection often unsuccessful when multiple devices are connected at the same time?
Possible causes: in use BluetoothDevice.connectGatt() perhaps BluetoothGatt.connect() Such establishment BluetoothGatt When connecting, at most one device can try to establish a connection at any time. If the establishment is initiated for multiple Bluetooth devices at the same time Gatt Connection request. If the previous device fails to connect, the subsequent device requests will be blocked forever without any connection callback. Recommendations: If you want to initiate connection requests for multiple devices, it is best to establish a request queue. The previous device requests to establish a connection, and the subsequent requests wait in the queue . If the connection is successful, the next connection request is processed. If the connection fails (for example, an error, or the connection timeout fails), it is called immediately BluetoothGatt.disconnect()/close()To release the establish connection request, and then process the next device connection request.
2. Why sometimes the connection is successful, but the service and characteristic values cannot be found, which affects the reception and transmission of data.
After the connection is successful, the BluetoothGatt.discoverServices()To discover services, and then set eigenvalues, etc., because the method is in the main It is executed in the thread. Therefore, in order to ensure the reliability of the connection process, it is recommended not to handle too many operations in the main thread(Especially frequency Complex drawing operation).
3. Why did you disconnect after a while after the connection was successful?
In fact, this problem is not mainly the problem of the client, so don't blindly find problems in the code. It is recommended to communicate with the hardware to optimize it ,If possible, the connection parameters of the equipment can be adjusted( ConnectionInterval(Connection interval) SlaveLatency(Slave delay or when slave Extension) SupervisionTimeout(Timeout or monitoring timeout), these three parameters are very important connection parameters in low-power Bluetooth, Decided together BLE The power consumption of general hardware devices will be APP When the connection is successful, take the initiative to update these three parameters to ensure the differences between different mobile phones Consistency, but APP The terminal cannot control these three parameters.
4. Maximum connections problem
The standard answer is 7. Why 7? We can find the basis from the underlying Bluetooth source code as shown in the figure below.
5. Use of connection api
Initiate Bluetooth Gatt connect BluetoothDevice.connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback),Here is a parameter autoConnect,If yes true If yes, the system will initiate a background connection. When the system finds a device, it will connect automatically. Usually, this process is very slow. by false If yes, it will be connected directly, usually faster. Again, BluetoothGatt.connect()Only one background connection can be initiated, not a direct connection Ground connection,Therefore, it is set when connecting autoConnect Parameter set to false,If you want to realize the reconnection function, do it manually. It's really not easy If you want to write it manually, use it Android-BLE Library, you basically have everything you want.
6. Why does the connection always report non-0 exceptions such as 133 and 19
Cause: it may not be released after connecting Bluetooth for the first time gatt The Bluetooth protocol stack is abnormal due to resource, resulting in 133 or 257 19 Equivalence is not 0: connection establishment failed due to protocol stack Suggestion: in onConnectionStateChange()Judgment in callback, if state Not 0(Disconnected),call gatt.close(),Manual release gatt Related resources
3, Data transmission problem
1. Why is the connection successful and sending data always fails?
reason: 1,First determine whether the main service is correct, and then check whether the set read and write characteristic values are correct 2,because BLE It takes time to discover services and set features and notifications, so you can't send data immediately after the connection is successful. You can wait until onDescriptorWrite()During callback, or manually delay for a period of time before sending.
2. Why subcontracting
BLE4.0 Bluetooth sends data, with a maximum transmission of 20 at a time byte,If it is a general protocol command, such as switching lights, moving forward, left and right, etc., it is not necessary Subcontracting, if necessary, such as pictures BIN Documents, music and other large data files must be sent by subcontracting, BLE Already mentioned in the library It provides an interface for sending large data packets, which can be downloaded by small partners DEMO View usage.
Author: f2a928cacb8d
Link: https://www.jianshu.com/p/ea63a1d674ef
Source: Jianshu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, and for non-commercial reprint, please indicate the source.