我有一个在android 4.3和4.4上运行良好的应用程序。
应用程序将连接并与自定义蓝牙设备通信。
当我把Nexus5闪到棒棒糖上之后,突然我根本无法连接到设备。连接结果始终为133。这是日志:
D/BluetoothGatt﹕ connect() - device: 00:07:80:04:1A:5A, auto: true
D/BluetoothGatt﹕ registerApp()
D/BluetoothGatt﹕ registerApp() - UUID=xxxxxx-xxxx-xxxxx-xxxx-xxxxxxxx
D/BluetoothGatt﹕ onClientRegistered() - status=0 clientIf=6
D/BluetoothGatt﹕ onClientConnectionState() - status=133 clientIf=6 device=00:07:80:04:1A:5A
我的代码:
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
return false;
}
Handler handler = new Handler(Looper.getMainLooper());
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null
&& address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
handler.post(new Runnable() {
@Override
public void run() {
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
}
}
});
if (mConnectionState == STATE_CONNECTING) {
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
return false;
}
handler.post(new Runnable() {
@Override
public void run() {
mBluetoothGatt = device.connectGatt(BluetoothConnectService.this, true, mGattCallback);
}
});
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
有人知道吗?
最佳答案
所以我发现问题出在棒棒糖的运输选择上。
从here中可以看出BluetoothDevice.connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback)
函数正在调用BluetoothDevice.connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback, int transport)
将transport设置为transport_auto。
在我的情况下,因为我将始终使用传输设备(值为2)
我试图从代码中调用第二个方法,并将传输设置为transport\u le。
由于未知的原因,我不能直接调用它,所以我使用反射来调用它。
直到现在这对我来说还不错。
if(TTTUtilities.isLollipopOrAbove()) {
// Little hack with reflect to use the connect gatt with defined transport in Lollipop
Method connectGattMethod = null;
try {
connectGattMethod = device.getClass().getMethod("connectGatt", Context.class, boolean.class, BluetoothGattCallback.class, int.class);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
try {
mBluetoothGatt = (BluetoothGatt) connectGattMethod.invoke(device, BluetoothConnectService.this, false, mGattCallback, TRANSPORT_LE);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
} else {
mBluetoothGatt = device.connectGatt(BluetoothConnectService.this, true, mGattCallback);
}
如果你们对我的回答有任何疑问,请在评论中提问。
谢谢您。