gpt4 book ai didi

java - Android BLE 多连接

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:08 26 4
gpt4 key购买 nike

我正在尝试创建一个连接多个蓝牙低功耗设备并从其接收通知的应用程序。我想知道如何实现这一目标。每个连接都需要一个单独的线程吗?考虑到 API 的异步特性,我如何才能确保发现服务和设置通知的顺序有效。我目前正在使用此处提供的相同结构: https://developer.android.com/guide/topics/connectivity/bluetooth-le.html .这仅为单个连接设置。我能否保留此结构,即扩展 BluetoothLeService 类中的服务类并绑定(bind)到服务。我最近发现 Service 类是一个单例,所以我将如何创建我的 BluetootLeService 类的不同实例并接收广播并注册广播接收器/接收器以处理来自适当设备的更改。

最佳答案

I am wondering how this can be achieved

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

private Map<String, BluetoothGatt> connectedDeviceMap; 

服务中onCreate初始化 Map

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

然后在调用 device.connectGatt(this, false, mGattCallbacks); 之前连接到 GATT 服务器 检查设备是否已经连接。

  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, int status)你有方法BluetoothGatt参数上的连接对象,您可以从中获取设备 BluetoothGatt .和其他回调方法,如 public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)您将获得设备表格 gatt .

当需要writeCharacteristicwriteDescriptor时,获取BluetoothGatt来自 Map 的对象并使用 BluetoothGatt对象调用 gatt.writeCharacteristic(characteristic) gatt.writeDescriptor(descriptor)用于不同的连接。

Do I need a separate thread for each connection?

我认为您不需要为每个连接使用单独的Thread。只需运行 Service在后台线程上。

希望对您有所帮助。

关于java - Android BLE 多连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47404018/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com