【问题标题】:How to implement Android message handler pattern in standard Java?如何在标准 Java 中实现 Android 消息处理程序模式?
【发布时间】:2012-05-22 13:04:51
【问题描述】:

我正在编写一个通过蓝牙与 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顺序异步处理?

【问题讨论】:

    标签: java android multithreading event-handling streaming


    【解决方案1】:

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

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

    【讨论】:

    • 我想过这样做,但这是不得已而为之。如果存在,我更愿意使用更标准的 java 方法。
    • 我知道,这不是理想的解决方案...我只是在谷歌上搜索并找到了这个:code.google.com/p/simple-mq 也许它可以帮助你一点
    • 让它工作。实现了一个精简版,因为许多功能直接绑定到 android 平台并且必须删除。
    • @CodeFusionMobile 你能和我分享你的精简版吗?我也需要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多