如何实现在标准Java的Andr​​oid消息处理程序模式

如何实现在标准Java的Andr​​oid消息处理程序模式

本文介绍了如何实现在标准Java的Andr​​oid消息处理程序模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个Android应用程序通过蓝牙与电脑进行通信。在正常操作期间,它会发出短8字节的数据包的快速连续从电话到PC,典型地> 100Hz的

I'm writing an Android app that communicates with a PC via bluetooth. During normal operation, it sends out a rapid succession of short 8 byte packets from the Phone to the PC, typically at >100Hz.

在每个设备单独的线程中运行执行写入和读取。在code是这样的:

On each device, a separate thread is running that execute writes and reads. The code looks like this:

/**
 * 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的一面code几乎是相同的,只是使用的BluetoothSocket,而不是流连接。

The Android side code is almost identical, just using a BluetoothSocket instead of a Stream Connection.

最大的区别是在 onBTMessageRead(缓冲,字节);

Android的功能:

Android function:

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

PC服务器功能:

PC Server Function:

protected void onBTMessageRead(byte[] message, int length) {
        if (mEventListener != null) {
            mEventListener.onBTMessageRead(message, length);
        }
        // Release the buffer
        ByteBufferFactory.releaseBuffer(message);
    }

Android提供了处理器,活套/消息模式,允许消息在线程发送。这使得读出要尽可能快地发生,并且在另一个线程排队消息处理。我ByteBufferFactory确保资源的线程之间共享。

Android provides a handler-looper/message pattern that allows messages to be sent across threads. This allows the reads to happen as fast as possible and queues the message processing in another thread. My ByteBufferFactory ensures that the resources are shared properly between threads.

目前我只在PC端实现的事件监听器模式,但我想在PC端类似的消息传递模式了。目前,该事件侦听器陷入泥淖的ConnectedThread并造成重大通信延迟。

Currently I only have an event listener pattern implemented on the PC side, but I would like a similar message passing pattern on the PC side too. Currently the event listener is bogging down the ConnectedThread and causing major communication lag.

有没有办法从一个线程在java中发送邮件,并让他们在FIFO顺序另一个线程异步处理?

推荐答案

HM,也许你可以只是相关的东西复制出来机器人源 - code的?
您将至少需要:

hm, maybe you can just copy the relevant things out of Androids Source-Code?You will need at least:






  • Looper
  • Handler
  • Message
  • MessageQueue

如果它不工作开箱,可以考虑把它作为一个code-设计的准则

If it is not working out of the Box, consider to take it as a 'Code-Design-Guideline'

这篇关于如何实现在标准Java的Andr​​oid消息处理程序模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 13:04