我目前正在尝试实现一个类,用作蓝牙连接上传入数据的缓冲区:
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();
谁能看到我犯错误的地方?
答案 0 :(得分: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;
}
可以解决您的问题。