2011-12-31 98 views
0

使用阻塞隊列目前我正在試圖實現一個類作爲輸入數據通過藍牙連接的緩衝區的使用方法:創建緩衝區類中的Android

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

我有點擔心你的getSize方法。您確定要刪除隊列中的所有內容(如果超過20個),只是爲了獲得大小? – OldCurmudgeon 2011-12-31 14:23:55

+0

這只是爲了錯誤檢查。我忘了爲這篇文章發表評論。 – gtdevel 2011-12-31 14:45:35

回答

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; 
} 

會解決你的問題。

+0

感謝您的輸入Paul。 再次檢查問題後,我認爲我的問題在別處。 如果我從我的主要活動中聲明並調用緩衝區類,它將起作用。 它是當我在我的藍牙通信類中使用它時,它給我帶來麻煩。 再次感謝您的意見。 – gtdevel 2011-12-31 14:44:56