Android线程和异步任务

时间:2014-03-11 00:48:05

标签: java android multithreading asynchronous

所以我有一个线程,让我们称之为connectedThread它从输入流接收数据(可能是蓝牙,wifi,usb串口等),我想知道的是如何向线程发送中断导致它一直持续到同一个线程(connectedThread)中的某个方法完成生成结果。请参阅以下伪代码以帮助说明我的观点。

已连接线程:

    private class ConnectedThread extends Thread {
        //Bluetooth socket just a example could be any input stream.
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        public ConnectedThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the input and output streams, using temp objects because
            // member streams are final
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            byte[] buffer; // buffer store for the stream
            int bytes; // bytes returned from read()
            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    // Arbitrary size for input stream data buffer. 
                    buffer = new byte[3];
                    //Send a arbitrary command for device to respond 
                    mmOutStream.write(255);
                    bytes = mmInStream.read(buffer,0,buffer.length);
                    /* This is where I want to not hard code a time out but in fact,
                     * wait for mmInStream.read(buffer,0,buffer.length); 
                     * to finish then immediately proceed 
                     */
                    Thread.sleep(87);
                    // Send the obtained bytes to the message handler
                    mHandler.obtainMessage(MESSAGE_READ,buffer).sendToTarget();
                    }
                 catch (IOException e) {
                     break;
                 } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
         }
        /* Call this from the main activity to send data to the remote device */
        public void write(byte[] bytes) {
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) { }
        }
    }

}

摘要

正如我在上面的代码评论中所建议的那样。我希望当前正在执行的线程等待输入流数据完成填充缓冲区然后立即将结果发送到消息处理程序。特别是我不想使用Thread.sleep()命令,因为这会减慢进程。我已经强烈阅读了以下page,但没有找到解决我问题的方法。

0 个答案:

没有答案