Android BLE API奇怪的行为

时间:2014-06-23 10:02:16

标签: android bluetooth-lowenergy android-bluetooth

我连接到我的蓝牙低功耗设备,如下所述:https://developer.android.com/guide/topics/connectivity/bluetooth-le.html

  1. 我得到设备:

    @Override
    public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
    
        if(device.getName().startsWith("BLE device")){
            mDevice = device;
            mDevice.connectGatt(RGBLight.this, false, bgc);
    
    
        }
    }
    
  2. 从设备获取信息:

    public void onConnectionStateChange(final android.bluetooth.BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
           //My app should keep connection to the BLE device as long as app lives.
            RGBLight.this.gatt = gatt;
            gatt.discoverServices();
        }
    }
    
  3. 3.当连接gatt并发现服务时,我试图将消息队列发送到特征。

    new Thread(new Runnable() {
    
            @Override
            public void run() {
    
                if (mService == null)
                    mService = gatt.getService(UUID_SERVICE);
                if (mCharacteristic == null)
                    mCharacteristic = mService.getCharacteristic(UUID_CHAR);
    
    
    
                for(int i = 0; i < 100; i++){
    
    
                    int r = Color.red(colorParsed);
                    int g = Color.green(colorParsed);
                    int b = Color.blue(colorParsed);
                    int br = Color.blue(brParsed);
    
                    mCharacteristic.setValue(new byte[] { COMMAND_SET_RGBW, (byte) r, (byte) g, (byte) b, (byte) br, 0, 0, 0, 0 });
                    gatt.writeCharacteristic(mCharacteristic);
    
                    TimeUnit.MILLISECONDS.sleep(100);   
                    }               
                }
    
    
        }).start();
    

    当我运行此代码时,大多数命令都会丢失。执行速度约为每秒1个命令。并且LogCat中存在错误:

         06-23 12:34:25.627: E/bt-btif(18002): already has a pending command!!
    

    这种低速会恶化我的应用的用户体验。

    我调查了几天,发现了非常有趣的行为。如果我启动应用程序并快速发送消息队列,它可以快速工作。(每100毫秒1个命令)。但是在启动后10-15秒后它开始减速并再次出现错误消息:

         06-23 12:34:25.627: E/bt-btif(18002): already has a pending command!!
    

    也许某人已经遇到过这样的问题,并且有办法使用Android API或其他方式重置消息队列。

1 个答案:

答案 0 :(得分:0)

在继续之前,你必须等待onCharacteristicWritten,否则你就会充满缓冲区。 gatt.write返回的特征仅仅意味着它正在通过混合堆栈和空气。