【问题标题】:android bluetooth LE - Why does the onReadRemoteRssi not work?android bluetooth LE - 为什么 onReadRemoteRssi 不起作用?
【发布时间】:2013-11-17 01:47:15
【问题描述】:

我想在连接 gatt 后继续读取 rssi。代码如下:

final BluetoothDevice device = mBluetoothAdapter
        .getRemoteDevice(address);
if (device == null) {
    Log.w(TAG, "Device not found.  Unable to connect.");
    return false;
}

mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
boolean readRssiFlag = mBluetoothGatt.readRemoteRssi();
Log.i(TAG,"readRssiFlag: "+readRssiFlag);

mGattCallback 是这样的:

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        ....
        @Override
        public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
            Log.i(TAG,"rssi = " + rssi);
        }
        ...
    };

并且 onReadRemoteRssi 不起作用。 请告诉我如何修改代码,或其他读取rssi的解决方案!

感谢您的建议!

【问题讨论】:

    标签: android bluetooth-lowenergy rssi gatt


    【解决方案1】:
    private mRssiTimer;
    ....
    private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback()
    {
        @Override
       public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
       {
           if (newState == BluetoothProfile.STATE_CONNECTED)
           {            
              TimerTask task = new TimerTask()
             {
                @Override
                public void run()
                {
                   mBluetoothGatt.readRemoteRssi();
                }
             };
             mRssiTimer = new Timer();
             mRssiTimer.schedule(task, 1000, 1000);
          }
          else if (newState == BluetoothProfile.STATE_DISCONNECTED)
          {
             mRssiTimer.cancel();
          }
       }
      ....
    }
    

    【讨论】:

    • 这是我最初的想法,但我更喜欢建立连接后请求-回调循环的简单性。但是,有时在成功读取 rssi 操作后永远不会触发 rssi 回调,这会停止请求周期。这只发生在我使用 2 台设备时。
    【解决方案2】:
    mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
    Log.d(TAG, "Trying to create a new connection.");
    boolean readRssiFlag = mBluetoothGatt.readRemoteRssi();
    

    问题是您没有等到连接状态发生变化才调用 readRemoteRssi。 readRemoteRssi 调用的最早时间是在您收到 onConnectionStateChange 且 newState = 2(已连接)之后。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2021-06-21
      • 2020-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多