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