栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Android BLE多个连接

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android BLE多个连接

我想知道如何实现

要实现多个BLE连接,您必须存储多个

BluetoothGatt
对象并将这些对象用于不同的设备。要存储多个连接对象,
BluetoothGatt
可以使用
Map<>

private Map<String, BluetoothGatt> connectedDeviceMap;

在服务上

onCreate
初始化
Map

connectedDeviceMap = new HashMap<String, BluetoothGatt>();

然后,在呼叫

device.connectGatt(this, false, mGattCallbacks);
连接到 GATT Server
之前,请检查该设备是否已经连接。

  BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(deviceAddress);  int connectionState = mBluetoothManager.getConnectionState(device, BluetoothProfile.GATT);  if(connectionState == BluetoothProfile.STATE_DISConNECTED ){   // connect your device   device.connectGatt(this, false, mGattCallbacks);  }else if( connectionState == BluetoothProfile.STATE_ConNECTED ){   // already connected . send Broadcast if needed  }

BluetoothGattCallback
,如果连接状态 CONNECTED
然后存储
BluetoothGatt
于对象
Map
,并且如果连接状态 DISCONNECTED 然后将其删除形成
Map

        @Override    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {        BluetoothDevice device = gatt.getDevice();        String address = device.getAddress();        if (newState == BluetoothProfile.STATE_CONNECTED) { Log.i(TAG, "Connected to GATT server."); if (!connectedDeviceMap.containsKey(address)) {       connectedDeviceMap.put(address, gatt);   }  // Broadcast if needed Log.i(TAG, "Attempting to start service discovery:" +         gatt.discoverServices());        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { Log.i(TAG, "Disconnected from GATT server."); if (connectedDeviceMap.containsKey(address)){   BluetoothGatt bluetoothGatt = connectedDeviceMap.get(address);   if( bluetoothGatt != null ){        bluetoothGatt.close();        bluetoothGatt = null;   }    connectedDeviceMap.remove(address);      } // Broadcast if needed        }    }

类似地,

onServicesDiscovered(BluetoothGatt gatt, intstatus)
BluetoothGatt
在参数上具有连接对象的方法也可以从中获取设备
BluetoothGatt
。像
public voidonCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristiccharacteristic)
您这样的其他回调方法将获得设备表单
gatt

当您需要 writeCharacteristicwriteDescriptor时

BluetoothGatt
从获取对象
Map
并使用该
BluetoothGatt
对象调用
gatt.writeCharacteristic(characteristic)

gatt.writeDescriptor(descriptor)
不同的连接。

每个连接是否需要一个单独的线程?

我认为您不需要为每个连接使用单独的 线程 。只需

Service
在后台线程上运行。

希望这对您有所帮助。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/610048.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号