BLE的connect()和connectGatt的区别

connect()和connectGatt都是连接BLE设备的方法,但二者用法不同。

connectGatt是BluetoothDevice类下的方法,功能是向BLE设备发起连接,然后得到一个BluetoothGatt类型的返回值,利用这个返回值可以进行下一步操作。

connect是BluetoothGatt类下的方法,功能是re-connect,重新连接。如果BLE设备和APP已经连接过,但是因为设备超出了蓝牙的连接范围而断掉,那么当设备重新回到连接范围内时,可以通过connect()重新连接。

两个方法的逻辑上大体是这样的:

先使用connectGatt方法发起连接,连接状态的改变会回调callback对象中的onConnectionStateChange(需要自己定义一个BluetoothGattCallBack对象并重写onConnectionStateChange),并返回一个BluetoothGatt对象,这时BluetoothGatt已经实例化,下一次连接可以调用connect重新连接。

贴两张API的图

下面附上BluetoothGatt的API,可以看出,得到BluetoothGatt实例的方法就是调用connectGatt去发起连接

Android中,可以使用Bluetooth Low Energy(BLE)API扫描、连接断开连接BLE设备。以下是一些基本步骤: 1. 获取 BluetoothAdapter 对象:使用 BluetoothManager 获取 BluetoothAdapter 对象。 ```java BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); ``` 2. 检查蓝牙是否已启用:使用 isEnabled() 方法检查蓝牙是否已启用。 ```java if (!bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } ``` 3. 开始扫描:使用 startScan() 方法开始扫描BLE设备。可以使用 BluetoothLeScanner 对象进行扫描。 ```java BluetoothLeScanner scanner = bluetoothAdapter.getBluetoothLeScanner(); scanner.startScan(mScanCallback); ``` 4. 停止扫描:使用 stopScan() 方法停止扫描BLE设备。 ```java scanner.stopScan(mScanCallback); ``` 5. 连接设备:使用 BluetoothDevice 对象连接BLE设备。可以使用 connectGatt() 方法进行连接。 ```java BluetoothGatt mBluetoothGatt = bluetoothDevice.connectGatt(this, false, mGattCallback); ``` 6. 断开连接:使用 disconnect() 方法断开连接。 ```java mBluetoothGatt.disconnect(); ``` 7. 关闭 GATT 连接:使用 close() 方法关闭 GATT 连接。 ```java mBluetoothGatt.close(); ``` 以上是一些基本步骤来扫描、连接断开连接BLE设备。具体实现还需要根据具体需求进行调整完善。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值