My goal is to make an auto connection between Bluetooth Low Energy device and phone. I followed the sample code and I found the line
// We want to directly connect to the device, so we are setting the autoConnect parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
The above code means that false
uses to autoconnection. However, I found the API at here, it said that
BluetoothGatt connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback, int transport) Connect to GATT Server hosted by this device.
And I also tried two flags: true
and false
, and only true
works. I am using version >= Android 5.0. Has something inconsistent between code and API? Which flag is correct? Do I need note something if I want to make the auto connection?
This is my code
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;
}
BluetoothGatt.java
callsclientConnect
onIBluetoothGatt
, which comes from an.aidl
file, but I haven't found anything implementing that yet) – Vermilion