【问题标题】:android 4.3 BLE device getting auto disconnect after multiple connection attempts多次连接尝试后,android 4.3 BLE 设备自动断开连接
【发布时间】:2017-02-02 18:25:09
【问题描述】:

我正在为 Android 开发一个具有 BLE 功能的应用程序,它运行良好,除非我尝试多次连接和断开 BLE 设备。在几次成功的连接/断开尝试后,BLE 设备在随机时间间隔后直接调用断开功能,即使它首先连接。

public boolean connect(final String address)
{

  if (mBtAdapter == null || address == null) {
       Log.v("Notification", "BluetoothAdapter not initialized or unspecified address.");
       return false;
   }

   // Previously connected device.  Try to reconnect.
   //mBtDeviceAddress != null && address.equals(mBtDeviceAddress)&&
   if (deviceGatt.get(address) != null) {
       Log.v("Notification", "Trying to use an existing mBluetoothGatt for connection.");
       if (deviceGatt.get(address).connect()) {
           mConnectionState = STATE_CONNECTING;
           Log.v("Notification","Connection State :" +mConnectionState);
           return true;
       } else {
           return false;
       }
   }

   final BluetoothDevice device = mBtAdapter.getRemoteDevice(address);
   pairedDevice = device;
   if (device == null) {
       Log.v("Notification", "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.
   BluetoothGatt mBluetoothGatt = device.connectGatt(this,false,this.mGattCallBack);

   deviceGatt.put(address,mBluetoothGatt);

   Log.v("Notification", "Trying to create a new connection.");
   Log.v("Notification","Size of device gatt "+deviceGatt.size());
   mBtDeviceAddress = address;
   mConnectionState = STATE_CONNECTING;
   return true;
}

public boolean disconnect(BluetoothDevice device) {

   if (mBtAdapter == null || deviceGatt.get(device.getAddress()) == null) {
       Log.v("Notification", "BluetoothAdapter not initialized");
       return false;
   }
   //Log.v("Notification","Device Address : "+device.getAddress());
   deviceGatt.get(device.getAddress()).disconnect();
   //deviceGatt.get(device.getAddress()).close();
   return true;
}

【问题讨论】:

  • 问题解决了吗?
  • 问题仍然存在。如果可能,请帮我解决这个问题

标签: java android


【解决方案1】:

我不确定这是否适合您,但我发现如果没有调用通知或特征写入,bluetoothGatt 会在大约 4-7 分钟后自动断开连接。通过每 5 秒调用一次 BluetoothGatt.readRemoteRssi() 为我解决了这个问题。

@Override
public void onReadRemoteRssi(BluetoothGatt gatt,int rssi, int status){
    if (status == BluetoothGatt.GATT_SUCCESS)     
        System.out.println("onReadRemoteRssi: " + rssi);

    if (mBluetoothGatt != null) 
        myHandler.postDelayed(runnableReadRssi, 5000);
}

您还应该确保在不再需要后关闭每个 bluetoothGatt 并设置为 null。我了解到,如果您有超过 5 个 bluetoothGatts 处于活动状态,您将收到无法连接到 Gatt 服务器的错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-18
    相关资源
    最近更新 更多