【发布时间】:2013-12-10 10:42:42
【问题描述】:
我正在尝试编写一个搜索多个蓝牙 LE 设备的小型 android 应用程序 (4.4)。一旦找到需要连接的每个设备,然后尽可能快地不断读取每个设备的 RSSI。我一直试图让它与 6 台设备一起使用。我目前的代码如下:
public class BluetoothGatt extends Activity {
private BluetoothAdapter mBluetoothAdapter;
private static final int REQUEST_ENABLE_BT = 1;
int count = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
// Initializes Bluetooth adapter.
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
System.out.println("Adapter: " + mBluetoothAdapter);
BTScanStart();
}
// Start the Bluetooth Scan
private void BTScanStart() {
if (mBluetoothAdapter == null) {
System.out.println("Bluetooth NOT supported. Aborting.");
return;
} else {
if (mBluetoothAdapter.isEnabled()) {
System.out.println("Bluetooth is enabled...");
// Starting the device discovery
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, byte[] scanRecord) {
count++;
System.out.println("Found " + count + ":" + device + " " + rssi + "db");
device.connectGatt(null, false, mGattCallback);
if (count > 5) mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
};
// Gatt Callback
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
System.out.println(gatt.getDevice() + ": Connected.. ");
gatt.readRemoteRssi();
}
if (newState == BluetoothProfile.STATE_DISCONNECTED) {
System.out.println(gatt.getDevice() + ": Disconnected.. ");
}
}
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
System.out.println(gatt.getDevice() + " RSSI:" + rssi + "db ");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
gatt.readRemoteRssi();
}
};
}
我遇到以下问题:
1) 它成功连接到设备,但大约 5 秒后它们都断开连接,并出现“btm_sec_disconnected - 清除挂起标志”错误。有没有办法让他们保持联系?
2) 该代码适用于单个设备,但是当使用多个设备时,只有一个设备会定期打印 RSSI 更新,其他设备会随机更新,有些则根本不更新。
3) 我不确定调用 device.connectGatt 时应该提供什么上下文。
提前感谢您的想法!
【问题讨论】:
-
我还注意到,当调用 device.connectGatt(.. 六次时,连接的回调仅在前五次触发...
-
是的,我遇到了重复连接/断开单个设备的问题。最终,蓝牙需要重置。我认为这是 LE api 的问题。
-
检查调用方法的线程。我怀疑您的 onReadRemoteRssi() 是从 Binder 线程调用的,而您仍在处理隐含的 BTLE 服务调用。尝试将 gatt.ReadRemoteRssi() 发布到处理程序上,这样您就不会占用回调。
标签: java android bluetooth rssi gatt