(十六)深入理解蓝牙BLE之“建立连接过程和连接失败分析”

25 篇文章 86 订阅 ¥49.90 ¥99.00
  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
以下是 Android 手机蓝牙BLE 设备建立连接的代码示例: 1. 在 AndroidManifest.xml 文件中添加蓝牙权限: ```xml <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> ``` 2. 在 Activity 中初始化 BluetoothAdapter 对象: ```java private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); ``` 3. 扫描 BLE 设备并建立连接: ```java // 扫描时间 10 秒 private static final long SCAN_PERIOD = 10000; // 扫描回调 private final BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { // 根据设备名称或 MAC 地址过滤 if (device.getName() != null && device.getName().startsWith("BLE")) { // 停止扫描 bluetoothAdapter.stopLeScan(leScanCallback); // 建立连接 device.connectGatt(MainActivity.this, false, gattCallback); } } }; // GATT 回调 private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { if (newState == BluetoothProfile.STATE_CONNECTED) { // 连接成功,开始发现服务 gatt.discoverServices(); } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { // 连接断开 Log.i(TAG, "Disconnected from GATT server."); } } @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { // 服务发现成功,可以进行数据交互 Log.i(TAG, "Services discovered."); } else { Log.w(TAG, "onServicesDiscovered received: " + status); } } @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { if (status == BluetoothGatt.GATT_SUCCESS) { // 读取特征值成功 Log.i(TAG, "Characteristic read successfully."); } else { Log.w(TAG, "Characteristic read failed: " + status); } } }; // 开始扫描 BLE 设备 private void scanBLEDevice() { if (bluetoothAdapter == null) { Log.w(TAG, "Bluetooth not supported."); return; } // 如果正在扫描,则先停止扫描 bluetoothAdapter.stopLeScan(leScanCallback); // 开始扫描 bluetoothAdapter.startLeScan(leScanCallback); // 扫描 SCAN_PERIOD 后停止扫描 new Handler().postDelayed(new Runnable() { @Override public void run() { bluetoothAdapter.stopLeScan(leScanCallback); } }, SCAN_PERIOD); } ``` 注意:在建立连接之前需要先扫描 BLE 设备,扫描到符合条件的设备后才能进行连接。在连接建立成功后,需要调用 `discoverServices()` 方法发现设备的服务,然后才能进行数据交互。以上代码仅供参考,实际开发中需要根据具体需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GuoFeng.Wan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值