如何在标准Java中实现Android消息处理程序模式?

我正在写一个通过蓝牙与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端代码几乎完全相同,只使用BluetoothSocket而不是Stream Connection。

最大的区别在于onBTMessageRead(buffer, bytes);

Androidfunction:

 protected void onBTMessageRead(byte[] buffer, int length) { if (mHandler != null) { mHandler.obtainMessage(BluetoothService.MESSAGE_READ, length, -1, buffer).sendToTarget(); } } 

PC服务器function:

 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顺序在另一个线程中异步处理它们?

嗯,也许你可以从Androids Source-Code中复制相关的东西? 你至少需要:

  • 尺蠖
  • 处理器
  • 信息
  • 的MessageQueue

如果没有开箱即用,请考虑将其作为“代码设计指南”