【发布时间】:2017-03-02 14:06:13
【问题描述】:
我的目标是在蓝牙低功耗设备和手机之间建立自动连接。我按照示例代码找到了这条线
// We want to directly connect to the device, so we are setting the autoConnect parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
以上代码表示false 用于自动连接。但是,我在here找到了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;
}
【问题讨论】:
标签: android bluetooth bluetooth-lowenergy bluetooth-gatt