我想写一个小的Android应用程序(4.4),它搜索几个蓝牙LE设备。一旦找到需要连接的设备,然后不断读取每个设备的RSSI即可。我一直在试图让这个6设备工作。我当前的代码如下:蓝牙LE Gatt连接Android 4.4读取实时RSSI
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()发布到一个处理程序上,这样就不会影响回调。 –