0

我的BLE与Android手机之间的连接两个选项:哪种模式可以实现Bluetooth Low Energy和Android手机之间的稳定连接?

connectGatt(this, false, mGattCallback); // If We want to directly connect to the device 
connectGatt(this, true, mGattCallback); // If We want to automatically connect (in background) to the device 

我测试了这两种方法:第一种是比较快的连接,但它不允许在后台重新连接。但是,在这个问题上,我认为稳定的联系。哪种方法在两种方法中更稳定?如果我想要更稳定的连接,你能向我建议这样做的方法吗?感谢所有

这是我的全部代码

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()) { 
       Log.d(TAG, "Call connect function"); 
       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); 
     new Handler(getMainLooper()).post(new Runnable() { 
      @Override 
      public void run() { 
       if (device != null) { 
        Log.d(TAG, "Connect connectGatt"); 
        mBluetoothGatt = device.connectGatt(getApplicationContext(), true, mGattCallback); 
       } 
      } 
     }); 

     mBluetoothDeviceAddress = address; 
     mConnectionState = STATE_CONNECTING; 
     return true; 
    } 

回答

0

我会去与AUTOCONNECT =真。然后,如果断开连接,您将不需要执行任何操作来重新连接,并且它将永久重试以保持连接正常。但是,您必须监听蓝牙状态更改,并在蓝牙重新启动时重新连接。请注意这个错误:https://code.google.com/p/android/issues/detail?id=69834

但是,由于Android代码中的错误以及蓝牙控制器中的很多蓝牙芯片制造商的代码,您将永远无法获得100%稳定的BLE连接。

+0

谢谢。但我测试这两个选项和autoConnect = false看起来更稳定。我不知道这是否正确。 – Jame

+0

你能详细说明你的意思是更稳定吗?一个连接启动并运行该特定连接的稳定性并不取决于是否使用autoConnect。 – Emil

+0

抱歉,延迟回复。稳定的连接意味着它会保持连接,直到我呼叫断开功能。然而,就我而言,我连接了BLE设备,大约3秒钟,它会自动断开连接(仅仅一段时间) – Jame

相关问题