android服务的aidl方法将数据放到LinkedBlockingQueue中,从workerthread中获取数据错误

时间:2013-11-22 14:12:29

标签: android multithreading aidl

我正在使用android aidl。我有一种将数据放入队列的方法,以及一个从中获取数据的读取线程。

private static LinkedBlockingQueue<int[]> mWriteQueue = new LinkedBlockingQueue<int[]>();

private final ISendService.Stub mBinder = new ISendService.Stub() {
@Override
public void writeData(int[] data) throws RemoteException {
    try {
            mWriteQueue.put(data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

private class WriteThread extends Thread {
    public void run() {
        while(true){
            try {
                int[] data = mWriteQueue.take();
Log.e(TAG, "mWriteQueue take:" + ByteUtils.toHexString(data));
} catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在UI中,单击一个按钮以执行代码:

for(int i = 0; i < 10; i++) {
    try {
        mSendService.writeData(data);
        Log.e(TAG, "write data:" + ByteUtils.toHexString(data));
    } catch (Exception e) {
        e.printStackTrace();
    }  
}

结果:

write data:0x51 0x51 0x01 0x08
write data:0x51 0x51 0x02 0x08
write data:0x51 0x51 0x03 0x08
write data:0x51 0x51 0x04 0x08
write data:0x51 0x51 0x05 0x08
write data:0x51 0x51 0x06 0x08
write data:0x51 0x51 0x07 0x08
write data:0x51 0x51 0x08 0x08
write data:0x51 0x51 0x09 0x08
write data:0x51 0x51 0x0a 0x08


mWriteQueue take:0x51 0x51 0x01 0x08
mWriteQueue take:0x51 0x51 0x0a 0x08
mWriteQueue take:0x51 0x51 0x0a 0x08
mWriteQueue take:0x51 0x51 0x0a 0x08
mWriteQueue take:0x51 0x51 0x0a 0x08
mWriteQueue take:0x51 0x51 0x0a 0x08
mWriteQueue take:0x51 0x51 0x0a 0x08
mWriteQueue take:0x51 0x51 0x0a 0x08
mWriteQueue take:0x51 0x51 0x0a 0x08
mWriteQueue take:0x51 0x51 0x0a 0x08

来自take的数据错误,我在java文档中看到,take应删除该项目。我在mWriteQueue.put(data);之前打印数据以确保数据正确无误。

1 个答案:

答案 0 :(得分:0)

我感到惭愧。 我解决了这个问题。 谢谢玉皇大帝。 使用     mWriteQueue.put(data.clone());