这个问题通常是由于连接时间超时引起的。可以通过以下步骤解决这个问题:
BluetoothGatt mGatt = device.connectGatt(this, false, mGattCallback);
mGatt.connect();
mGatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH);
mGatt.setTimeout(5000);
在这个示例中,我们将连接超时时间设置为5秒钟。
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
private int mConnectionState = STATE_DISCONNECTED;
private BluetoothGatt mBluetoothGatt;
private final BluetoothGattCallback mGattCallback =
new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
mConnectionState = STATE_CONNECTED;
mBluetoothGatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
mConnectionState = STATE_DISCONNECTED;
mBluetoothGatt.close();
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
// service discovery successful
} else {
// service discovery unsuccessful
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
// characteristic read successful
} else {
// characteristic read unsuccessful
}
}
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
// characteristic write successful
} else {
// characteristic write unsuccessful
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
// characteristic value changed
}
};
public void connect(String address) {
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null
上一篇:Android蓝牙-连接监视器认为连接已断开,但实际上并未断开
下一篇:Android蓝牙程序在大约一分钟后停止接收字符。java.io.exception:BTSocketClosedReadReturn:-1