Android Bluetooth BLE(2)

The last article wrote about searching for Bluetooth devices, and this article about connecting devices.

In the onLeScan callback, install the device into a collection for display. Note that the device will be repeatedly scanned. Because the device continuously sends out broadcasts, it is necessary to filter out the repeated devices. (It should be noted that the onLeScan callback method is performed in an asynchronous thread. If you need to refresh the UI, you need to refresh the UI interface in the main thread.)

I will not write about the interface display list.

The following is the connection method.
Core method: connectGatt(Context context, boolean autoConnect,BluetoothGattCallback callback); the
first parameter is the context object, the second parameter is whether to connect automatically, and the third parameter is the callback of the connection. The return value is a BluetoothGatt object, through which you can communicate with the device.

Code:

device.connectGatt(MainActivity.this,false,gattCallback);

 private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        //链接状态改变回调此方法。
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            switch (newState){
                case BluetoothGatt.STATE_CONNECTED://已连接
                    Log.e("lee","已连接");
                    break;
                case BluetoothGatt.STATE_CONNECTING://连接中
                    Log.e("lee","连接中");
                    break;
                case BluetoothGatt.STATE_DISCONNECTED://已断开
                    Log.e("lee","已断开");
                    break;
                case BluetoothGatt.STATE_DISCONNECTING://断开中
                    Log.e("lee","断开中");
                    break;
            }
        }
    };

This completes the connection of the Bluetooth device.

Guess you like

Origin blog.csdn.net/qq77485042/article/details/109310902