0

我目前正在尝试实现一个类以用作通过蓝牙连接传入数据的缓冲区:

public class IncomingBuffer {

private static final String TAG = "IncomingBuffer";

private BlockingQueue<byte[]> inBuffer;

public IncomingBuffer(){
    inBuffer = new LinkedBlockingQueue<byte[]>();
    Log.i(TAG, "Initialized");
}

public  int getSize(){
    int size = inBuffer.size();
    byte[] check=new byte[1];
    String total=" ";
    if(size>20){
        while(inBuffer.size()>1){
            check=inBuffer.remove();
            total=total+ " " +check[0];
        }
        Log.i(TAG, "All the values inside are "+total);
    }
    size=inBuffer.size();
    return size;
}

//Inserts the specified element into this queue, if possible. Returns True if successful.
public boolean insert(byte[] element){
    Log.i(TAG, "Inserting "+element[0]);
    boolean success=inBuffer.offer(element);
    return success;
}

//Retrieves and removes the head of this queue, or null if this queue is empty.
public byte[] retrieve(){       
    Log.i(TAG, "Retrieving");
    return inBuffer.remove();

}

// Retrieves, but does not remove, the head of this queue, returning null if this queue is empty.
public byte[] peek(){

    Log.i(TAG, "Peeking");
    return inBuffer.peek();
}   
}

我遇到了这个缓冲区的问题。每当我添加一个字节数组时,缓冲区中的所有字节数组都与我刚刚添加的字节数组相同。

我已经尝试在我的其余代码中使用相同类型的阻塞队列(没有使其成为自己的类),它工作正常。问题似乎出在我使用此类时。

我声明类的方式如下:

private IncomingBuffer ringBuffer;
ringBuffer = new IncomingBuffer();

谁能看到我在哪里犯了错误?

4

1 回答 1

1

你有可能每次都添加相同的内容吗? byte[]

也许:

public boolean insert ( byte[] element ) {
  Log.i(TAG, "Inserting "+element[0]);
  // Take a copy of the element.
  byte[] b = new byte[element.length];
  System.arraycopy( element, 0, b, 0, element.length );
  boolean success = inBuffer.offer( b );
  return success;
}

会解决你的问题。

于 2011-12-31T14:15:41.693 回答