Моя цель - установить автоматическое соединение между устройством Bluetooth Low Energy и телефоном. Я следовал примеру кода и нашел строку
// We want to directly connect to the device, so we are setting the autoConnect parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Приведенный выше код означает, что false
использует для автоматического подключения. Тем не менее, я нашел API на здесь, там говорилось, что
BluetoothGatt connectGatt (контекстный контекст, логическое автоконнект, обратный вызов BluetoothGattCallback, int транспорт) Подключитесь к серверу GATT, размещенному на этом устройстве.
И я также попробовал два флага: true
и false
, и только true
работает. Я использую версию> = Android 5.0. Есть что-то несовместимое между кодом и API? Какой флаг правильный? Нужно ли что-то записывать, если я хочу установить автоматическое соединение?
Это мой код
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()) {
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, true, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}