Low Power Bluetooth official documentation

This article is a reference to the official website, and then add their own practice of understanding to complete! For those of you who missed the last one, you can read the previous one, which is a series. Website address: developer.android.com/guide/topic…

Android 4.3 (API 18) introduces Low-power Bluetooth, which allows applications to query surrounding devices, query device services, and transfer information.

Key terms and concepts

  • GATT Generic Attribute Profile

    A GATT profile is a transport data specification that is a general specification for sending and receiving short pieces of data called attributes over a BLE link. Currently, all low-power application profiles are based on GATT

  • Bluetooth SIG (Bluetooth Technology Alliance)

    Many configuration files are defined for low-power devices. A configuration file is a specification of how a device works in a particular application. Devices can implement multiple profiles. For example, a device can contain a heart rate monitor and a battery level detector.

    Normative defining

  • ATT Attribute Protocol

    GATT is based on the Attribute Protocol (ATT). Also known as GATT/ATT. ATT has been optimized for use on BLE devices. To do this, it uses as few bytes as possible. Each attribute is uniquely identified by a universal unique identifier (UUID). Attributes transmitted by ATT are formatted as features and services

  • Characteristics of the

    Features contain a single value and 0 to N descriptors that describe eigenvalues. Eigenvalues can be called types. It’s like a class. (It is the main operation when communicating with BLE device)

  • The descriptor

    Is a defined property used to define eigenvalues. It’s used to describe the eigenvalues. For example, descriptors can specify human-readable descriptions, acceptable ranges of eigenvalues, or specific units of measure for eigenvalues

  • service

    A service contains a set of eigenvalues. For example, we could use a service called “heart rate Monitor,” which includes features like “heart rate measurement.” A list of services based on existing GATT profiles can be found on bluetooh.org.

Roles and Responsibilities

The roles and responsibilities of an application when an Android device interacts with a BLE device

  • Central and peripheral equipment.
  • GATT server and GATT client. How can two devices communicate with each other after establishing a connection

BLE permissions

BLUETOOTH requires this permission for BLUETOOTH communication, such as requesting a connection, receiving a connection, and transmitting data.

If you also need to discover or manipulate Bluetooth Settings, you need to declare the BLUETOOTH_ADMIN permission. The prerequisite for using this permission is BLUETOOTH permission.

To declare that our application is only for BLE enabled devices, we need to make the following declaration in the manifest file

<uses-feature android:name = "android.hardware.bluetooth_le" android:required = true />
Copy the code

If we want our application to run on devices that do not support BLE, we can simply change true to false.

You can also make judgments in code

if(! getPackageManager().hasSystemFeature(PackgeManger.FEATURE_BLUETOOTH_LE)){BLE devices are not supported
}
Copy the code

BLE is usually associated with location, so you also need to declare location permissions ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION without which scanning will not return any results.

Set the BLE

  1. Get the BluetoothAdapter

    BluetoothAdapter represents the device’s own BluetoothAdapter, there is only one BluetoothAdapter in the whole system and our applications can interact with this object.

    The retrieval method here is obtained through BluetoothManager

    BluetoothManager bluetoothManger = getSystemSerive(Context.BULETOOTH_SERVIcE);
    BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();
    Copy the code
  2. Enable Bluetooth devices

    In fact, these and ordinary Bluetooth startup is the same.

    IsEnable () checks whether Bluetooth is currently enabled

    Bluetoothadapter.action_request_enable to start

  3. Find BLE devices

    This is not the same as discovering a normal Bluetooth device

    // Through the Adapter startLeScan(callBack); Method to enable scanning
    // If we have a specified Bluetooth device availableSartLeScan (UUID [], BluetoothAdapter. LeScanCallBakc) designated BLe by UUIDBluetoothLeScanner is a special object that BluetoothLeScanner uses to enable bluetooth scanning for low power consumption
    BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner();
    // This method can have parameters to filter the low-power Bluetooth to be scanned, more on that later
    scanner.startScan();
    
    Copy the code

    Only ordinary Bluetooth devices or BLE devices can be scanned separately. No method can be performed simultaneously

Connect to the GATT server

The first step in communicating with a BLE device is to connect to it, namely to the DEVICE’s GATT service. The connectGatt() method takes three parameters: the Context object autoConnect (indicating whether it is connected to a BLE device when available) and a callback in which all interaction takes place.

Calling this method returns a BluetoothGatt object through which to interact with BLE devices. The result of the interaction is triggered in the callback method.

public class BluetoothLeService extends Service{
    private final static String TAG = BluetoothLeService.class.getSimpleName();
    private BluetoothManger bluetoothManger;
    private BluetoothAdapter bluetoothAdapter;
    private String bluetoothDeviceAddress;
    private BluetoothGatt bluetoothGatt;
    private int connectionState = STATE_DISCONNECTED;
    
    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNETING = 1;
    private static final int STATE_CONNECTED = 2;
    
    public final static String ACTION_GATT_CONNECTED = "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED = "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
    public final static String ACTION_GATT_SERVICES_DISCOVERED = "com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
    public final satic String ACTION_DATA_AVAILABLE = "com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
    public final static String EXTRA_DATA = "com.example.bluetooth.le.EXTRA_DATA";
    
    public final static UUID UUID_HEART_RATE_MEASUREMENT = UUID.formString(SampleGattAttributes.HEART_RATE_MEASURMENT);
    
    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback(){
        // When your central device is connected to a BLE device, this method will be called back.
        @Override
        public viod onConnectionStateChange(BluetoothGatt gatt,int status,int newState){
            String intenAction;
            if(newState == BluetoothProfile.STATE_CONNECTED){
                intentaction = ACTION_GATT_CONNECTED;
                connectionState = STATE_CONNECTED;
                broadcastUpdate(intentAction);
                // Connect to the Service
                bluetoothGatt.discoverServices();
            }else if(newState = BluetoothProfile.STATE_STATE_DISCONNECTED{ intentAction = ACTION_GATT_DISCONNECTED; connectionState = STATE_DISCONNECTED; broadcastUpdate(intentAction); }}@Override
        // This method is triggered when the service is found, and then you need to find the service that you and BLE agreed on
        public void onServicesDiscovered(BluetoothGatt gatt,int status){
            if(status == BluetoothGatt.GATT_SUCCESS){ broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED); }}public void onCharacteristicREad(。。。){}... }}Copy the code

When a particular callback is triggered, the appropriate broadcastUpdate() helper method is called and passed the action to it. The specific data parsing format is performed according to the configuration file specification (a specification agreed upon between you and your BLE device)

The connection is opened, then the corresponding connection callback is triggered, then the service is discovered, then the discovery service callback is triggered, the eigenvalues inside the service are retrieved, and commands are read and written to the service (a specification that is constrained by BLE). That’s the process. It’s very simple.

Read the BLE properties

Once our Android device connects to the GATT server and discovers the service, we can read or write properties from supported locations.

Remember to turn off the device, bluetoothgat.close ();

A library for Bluetooth frameworks: github.com/Alex-Jerry/…