Ice*_*tan 3 java android broadcastreceiver bluetooth-lowenergy
我正在尝试创建一个应用程序,该应用程序可以连接并接收来自多个蓝牙低能耗设备的通知。我想知道如何实现这一目标。每个连接是否需要一个单独的线程?考虑到API的异步性质,如何确保能够按发现的顺序发现服务并设置通知。我目前正在使用此处提供的相同结构:https: //developer.android.com/guide/topics/connectivity/bluetooth-le.html。此设置仅用于单个连接。我将能够保持这种结构,即在BluetoothLeService类中扩展Service类并绑定到该服务。我最近发现Service类是一个单例,因此我将如何创建BluetootLeService类的不同实例并接收广播并注册广播接收器/接收器以处理来自适当设备的更改。
我想知道如何实现
要实现多个BLE连接,您必须存储多个BluetoothGatt对象并将这些对象用于不同的设备。要存储多个连接对象,BluetoothGatt可以使用Map<>
private Map<String, BluetoothGatt> connectedDeviceMap;
Run Code Online (Sandbox Code Playgroud)
在服务上onCreate初始化Map
connectedDeviceMap = new HashMap<String, BluetoothGatt>();
Run Code Online (Sandbox Code Playgroud)
然后,在呼叫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
}
Run Code Online (Sandbox Code Playgroud)
上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
}
}
Run Code Online (Sandbox Code Playgroud)
同样,在参数上onServicesDiscovered(BluetoothGatt gatt, int status)有BluetoothGatt连接对象的方法也可以从中获取设备BluetoothGatt。像public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic)您这样的其他回调方法将获得设备表单gatt。
当您需要writeCharacteristic或writeDescriptor时,BluetoothGatt从获取对象Map并使用该BluetoothGatt对象调用gatt.writeCharacteristic(characteristic) gatt.writeDescriptor(descriptor)不同的连接。
每个连接是否需要一个单独的线程?
我认为您不需要为每个连接使用单独的线程。只需Service在后台线程上运行。
希望这对您有所帮助。