我正在编写一个通过蓝牙与 PC 通信的 Android 应用程序。在正常操作期间,它会从电话向 PC 快速发送一连串短的 8 字节数据包,通常频率 >100Hz。
在每个设备上,一个单独的线程正在运行,执行写入和读取。代码如下所示:
/**
* The Class ProcessConnectionThread.
*/
public class ConnectedThread extends Thread {
/** The m connection. */
private StreamConnection mmConnection;
InputStream mmInputStream;
OutputStream mmOutputStream;
private boolean mmCanceled = false;
/**
* Instantiates a new process connection thread.
*
* @param connection
* the connection
*/
public ConnectedThread(StreamConnection connection) {
mmConnection = connection;
// prepare to receive data
try {
mmInputStream = mmConnection.openInputStream();
mmOutputStream = mmConnection.openOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run() {
byte[] buffer;
int bytes;
// Keep listening to the InputStream while connected
while (!mmCanceled) {
try {
buffer = ByteBufferFactory.getBuffer();
// Read from the InputStream
bytes = mmInputStream.read(buffer);
if(bytes > 0)
onBTMessageRead(buffer, bytes);
else
ByteBufferFactory.releaseBuffer(buffer);
} catch (IOException e) {
MyLog.log("Connection Terminated");
connectionLost();//Restarts service
break;
}
}
if(!mmCanceled){
onBTError(ERRORCODE_CONNECTION_LOST);
}
}
/**
* Write to the connected OutStream.
*
* @param buffer
* The bytes to write
* @param length
* the length
*/
public void write(byte[] buffer, int length) {
try {
mmOutputStream.write(buffer, 0, length);
// Share the sent message back to the UI Activity
onBTMessageWritten(buffer, length);
} catch (IOException e) {
MyLog.log("Exception during write:");
e.printStackTrace();
}
}
/**
* Cancel.
*/
public void cancel() {
try {
mmCanceled = true;
mmInputStream.close();
mmConnection.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Android 端代码几乎相同,只是使用了蓝牙套接字而不是流连接。
最大的区别在于onBTMessageRead(buffer, bytes);
安卓功能:
protected void onBTMessageRead(byte[] buffer, int length) {
if (mHandler != null) {
mHandler.obtainMessage(BluetoothService.MESSAGE_READ, length, -1,
buffer).sendToTarget();
}
}
PC服务器功能:
protected void onBTMessageRead(byte[] message, int length) {
if (mEventListener != null) {
mEventListener.onBTMessageRead(message, length);
}
// Release the buffer
ByteBufferFactory.releaseBuffer(message);
}
Android 提供了一个 handler-looper/message 模式,允许跨线程发送消息。这允许读取尽可能快地发生,并将消息处理排队在另一个线程中。我的 ByteBufferFactory 确保资源在线程之间正确共享。
目前我只在 PC 端实现了一个事件侦听器模式,但我也希望在 PC 端也有一个类似的消息传递模式。目前,事件侦听器使 ConnectedThread 陷入困境并导致严重的通信延迟。
有没有办法从java中的一个线程发送消息并让它们在另一个线程中以FIFO顺序异步处理?