“This is the fifth day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

1 introduction

The rise of BLE bluetooth is mainly due to the popularity of wearable devices in recent years. Due to the high power consumption of traditional Bluetooth, it cannot meet the requirements of wearable devices for battery life. So most wearable devices use Bluetooth 4.0, or BLE Bluetooth technology. BLE(Bluetooth Low Energy), the main features are fast search, fast connection, ultra-low power to maintain connection and data transmission. Disadvantages: Low data transfer rate, especially during Android development, BLE bluetooth data pack is up to 20 bytes, so it is best not to use BLE to transfer large amounts of data on Android.

2 Permission Application

Android phones involve Bluetooth permissions, Bluetooth development needs to add permissions in the Androidmanifest.xml file:

<! BLUETOOTH permissions - - - > < USES - permission android: name = "android. Permission. BLUETOOTH" / > < USES - the permission android:name="android.permission.BLUETOOTH_ADMIN" />Copy the code

For Android 6.0 and above, you need to add an obscure location permission

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Copy the code

Allow this permission in the mobile phone rights management. Otherwise, the device cannot be searched.

3 Enabling Bluetooth

Before searching the device, you need to ask to turn on the bluetooth of the phone, and the key code is as follows:

Private BluetoothAdapter mBluetoothAdapter = bluetoothAdapter.getDefaultAdapter (); // Ask to open bluetooth if (mBluetoothAdapter! = null && ! mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); } // Override protected void onActivityResult(int requestCode, int resultCode, int requestCode, int resultCode) Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); If (requestCode == 1) {if (resultCode == RESULT_OK) {totoast. MakeText (this, "LENGTH_SHORT ", totoast).show(); } else if (resultCode == RESULT_CANCELED) {toasts. MakeText (this, "no bluetooth privileges ", toasts.LENGTH_SHORT).show(); finish(); }}}Copy the code

4 Searching for Devices

This article mainly aims at BLE development of bluetooth, so use mBluetoothAdapter. StartLeScan (LeScanCallback callback) scanning BLE bluetooth devices. The method is as follows:

mBluetoothAdapter.startLeScan(callback); private LeScanCallback callback = new LeScanCallback() { @Override public void onLeScan(BluetoothDevice device, Int arg1, byte[] arg2) {if(device.getname () == "targetDevice name "){// get the targetDevice targetDevice = device; }}};Copy the code

5 Connecting Devices

By scanning BLE devices, the targetDevice is identified as targetDevice according to the device name. The next step is to connect to the targetDevice. Stop searching for Bluetooth before connecting the device.

mBluetoothAdapter.stopLeScan(callback);
Copy the code

Note: It generally takes a certain amount of time to stop the search, and it is better to call the stop search function with a delay of 100ms to ensure that the system can completely stop searching bluetooth devices. Start the connection process after you stop searching.

The BLE bluetooth connection method is relatively simple, just call the connectGatt method, the function prototype is as follows:

Public BluetoothGatt connectGatt (Context Context, Boolean autoConnect, BluetoothGattCallback Callback);Copy the code

Parameter description: Returned value BluetoothGatt: BLE Bluetooth connection management class, responsible for communicating with devices. This class is described in more detail later. Boolean autoConnect: False is recommended to improve connection speed. BluetoothGattCallback Callback Connection callback, an important parameter of BLE Bluetooth communication, the core part of BLE communication.

6 Device Communication

After establishing a connection with the device and communicating with the device, the whole communication process is completed in the asynchronous callback function of BluetoothGattCallback. The main callback functions in BluetoothGattCallback are as follows:

private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status,
                int newState) {
        }
        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic, int status) {

            super.onCharacteristicWrite(gatt, characteristic, status);
        }

        @Override
        public void onDescriptorWrite(BluetoothGatt gatt,
                BluetoothGattDescriptor descriptor, int status) {

        };

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {

        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt,
                BluetoothGattCharacteristic characteristic) {
            }
    };
Copy the code

The above callback functions are essential to BLE development, and the meaning of each function and when it is called will be explained in the next steps.

6.1 Waiting for the Device to Be Connected Successfully

When calling targetdDevice. ConnectGatt (context, false, gattCallback) after the system will initiate and BLE bluetooth connection, if successfully connect to the device will callback onConnectionStateChange method, The processing process is as follows:

@Override public void onConnectionStateChange(BluetoothGatt gatt, int status, Int newState) {if (newState == bluetoothgatt.state_Connected) {log.e (TAG, "start scanning service on device connection "); / / start scanning service, android bluetooth development. One of the important steps mBluetoothGatt discoverServices (); } if (newState == bluetoothgatt.state_disconnected) {// connection disconnection /* Processing if connection disconnection */}};Copy the code

NewState == BluetoothGatt.STATE_CONNECTED Indicates that the device is successfully connected.

6.2 Enabling the Scan Service

mBluetoothGatt.discoverServices();
Copy the code

OnServicesDiscovered () onServicesDiscovered() onServicesDiscovered() onServicesDiscovered() onServicesDiscovered() onServicesDiscovered() onServicesDiscovered()

@Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { private List<BluetoothGattService> servicesList; / / get service list servicesList = mBluetoothGatt getServices (); }Copy the code

BLE bluetooth protocol of data communication mode using BluetoothGattService, BluetoothGattCharacteristic and BluetoothGattDescriptor three main type of communication.

BluetoothGattService is a service for short. It is a unit of THE BLE device protocol stack. A Bluetooth device protocol stack usually consists of one or more bluetoothGattServices.

BluetoothGattCharacteristic referred to as “characteristics, a service includes one or more characteristics, features as the basic unit of data. A BluetoothGattCharacteristic feature contains a data value and the additional BluetoothGattDescriptor about characteristic description.

BluetoothGattDescriptor Class used to describe a feature, which also contains a value.

6.3 get BluetoothGattCharacteristic is responsible for the communication

BLE Bluetooth development is mainly responsible for communication BluetoothGattService completed. When and is called a communication service. The communication service can be obtained from the UUID provided by the hardware engineer. Obtain the information as follows:

BluetoothGattService service = mBluetoothGatt. GetService (UUID. FromString (" bluetooth module provides is responsible for the communication UUID string "));Copy the code

Communications services include BluetoothGattCharacteristic responsible for reading and writing, and is called notifyCharacteristic and writeCharacteristic respectively. The notifyCharacteristic is responsible for starting the listening, that is, starting the data receiving channel, and the writeCharacteristic is responsible for writing data. The specific operation mode is as follows:

BluetoothGattService service = mBluetoothGatt. GetService (UUID. FromString (" bluetooth module is responsible for the communication service provided by the UUID string ")); // For example: 49535343-fe7d-4ae5-8fa9-9fafd205e455 notifyCharacteristic = service.getCharacteristic(UUID.fromString("notify uuid")); writeCharacteristic = service.getCharacteristic(UUID.fromString("write uuid"));Copy the code

6.4 Enabling Listening

Enable listening, that is, establish the first data channel for communication with the device. In BLE development, the upper computer can only receive and send data with the lower computer after successfully enabling listening. You can enable listening as follows:

mBluetoothGatt.setCharacteristicNotification(notifyCharacteristic, true)
BluetoothGattDescriptor descriptor = characteristic
                            .getDescriptor(UUID
                                    .fromString
("00002902-0000-1000-8000-00805f9b34fb"));
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
Copy the code

If the listening is enabled successfully, the onDescriptorWrite() method of BluetoothGattCallback is called as follows:

@Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, Int status) {if (status == bluetoothgatt.gatt_success) {// bluetoothgatt_success has been enabled, and log.e (TAG, "successfully enabled listening ") can be written to devices; }};Copy the code

6.5 Writing Data

After the listening is successful, data is written to writeCharacteristic to communicate with the lower machine. The writing mode is as follows:

/ / value for PC sent down a machine instruction writeCharacteristic. SetValue (value); mBluetoothGatt.writeCharacteristic(writeCharacteristic)Copy the code

Where: value is usually the Hex format instruction, and its content is specified by the Bluetooth communication protocol for device communication.

6.6 Receiving Data

If the instruction is successfully written, the onCharacteristicWrite() method of BluetoothGattCallback is called to indicate that the data has been sent to the lower machine.

@Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, Int status) {if (status == bluetoothgatt.gatt_success) {log.e (TAG, "sent successfully "); } super.onCharacteristicWrite(gatt, characteristic, status); }Copy the code

If the sent data conforms to the communication protocol, the lower bit will reply the corresponding data to the higher bit. The data sent by the callback onCharacteristicChanged() is handled as follows:

@Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {/ / the value for the devices to send data, according to the data protocol parsing byte [] value = characteristic. The getValue (); }Copy the code

The communication with the device can be completed by sending instructions to the lower machine to obtain the reply data of the lower machine.

7 Disconnection

Disconnect from the device after the communication is complete. Call the following method to disconnect from the device:

mBluetoothGatt.disconnect();
    mBluetoothGatt.close();
Copy the code

Public account: Programmer Meow (focus on Android study notes, interview questions and IT information sharing)