0
我的BLE与Android手机之间的连接两个选项:哪种模式可以实现Bluetooth Low Energy和Android手机之间的稳定连接?
connectGatt(this, false, mGattCallback); // If We want to directly connect to the device
connectGatt(this, true, mGattCallback); // If We want to automatically connect (in background) to the device
我测试了这两种方法:第一种是比较快的连接,但它不允许在后台重新连接。但是,在这个问题上,我认为稳定的联系。哪种方法在两种方法中更稳定?如果我想要更稳定的连接,你能向我建议这样做的方法吗?感谢所有
这是我的全部代码
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
Log.d(TAG, "Call connect function");
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
//mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
new Handler(getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (device != null) {
Log.d(TAG, "Connect connectGatt");
mBluetoothGatt = device.connectGatt(getApplicationContext(), true, mGattCallback);
}
}
});
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
谢谢。但我测试这两个选项和autoConnect = false看起来更稳定。我不知道这是否正确。 – Jame
你能详细说明你的意思是更稳定吗?一个连接启动并运行该特定连接的稳定性并不取决于是否使用autoConnect。 – Emil
抱歉,延迟回复。稳定的连接意味着它会保持连接,直到我呼叫断开功能。然而,就我而言,我连接了BLE设备,大约3秒钟,它会自动断开连接(仅仅一段时间) – Jame