我正在为一个开源计步器编写一个BLE应用程序,到目前为止我有一个很烦人的问题:在BLE服务的BluetoothGattCallback void方法“onConnectionStateChange”中,参数“int newState”只能是这里记录的两个值之一,STATE_DISCONNECTED或STATE_CONNECTED:
问题是当我断开连接并重新尝试连接到我的BLE设备时,它可以工作,但是当它处于连接状态时我没有反馈。屏幕保持静止,从断开连接跳到连接,可能需要3秒到15秒才能完成。
因此,我的问题是,我可以直接访问BluetoothGattCallback的onConnectionStateChange方法并将“BluetoothProfile.STATE_CONNECTING”的值传递给它,以便状态“STATE_CONNECTING”的“else if”语句中的代码行执行吗?如果是这样,怎么样?
我已经附加了onConnectionStateChange和connect方法。它们与开发人员网站上提供的样本心率监测应用程序中提供的内容大致相同。我唯一的改变是STATE_CONNECTING的“else if”。
感谢。
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
}
else if (newState == BluetoothProfile.STATE_CONNECTING) {
intentAction = ACTION_GATT_CONNECTING;
mConnectionState = STATE_CONNECTING;
Log.i(TAG, "Attempting to connect to GATT server...");
broadcastUpdate(intentAction);
}
else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
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.i(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, false, mGattCallback);
Log.i(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
答案 0 :(得分:1)
原来我需要做的就是自己调用Gatt回调并创建一个私有静态int来传递给回调方法。
mGattCallback.onConnectionStateChange(mBluetoothGatt, GATT_INDETERMINATE, STATE_CONNECTING);
GATT_INDETERMINATE是
private static int GATT_INDETERMINATE = 8;
我确保BluetoothGattCallback类没有使用8,所以8是一个很好的值。 最后在onConnectionStateChanged中,我执行以下操作并使用标识操作字符串广播适当的意图。
else if (newState == BluetoothProfile.STATE_CONNECTING) {
intentAction = ACTION_GATT_CONNECTING;
mConnectionState = STATE_CONNECTING;
Log.i(TAG, "Attempting to connect to GATT server...");
broadcastUpdate(intentAction);
}