我的目标是在低功耗蓝牙设备和手机之间建立自动连接。我按照示例代码找到了这条线
// 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(Context context, boolean autoConnect, BluetoothGattCallback callback, int transport) 连接到此设备托管的 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;
}