大家好,所以我试图从蓝牙设备读取流,该流持续流式传输整数,如下所示:

-11
121
123
1234
-11


我可以使用网上找到的所有代码进行所有工作,但是要进行一些处理,数字需要是整数(而不是字符串),parseInt占用了过多的CPU,因此我尝试使用无用的缓冲流。

这是当前方法:

 void beginListenForData()
        {
final Handler handler = new Handler();
  final byte delimiter = 10; //This is the ASCII code for a newline character

        stopWorker = false;
        readBufferPosition = 0;
        readBuffer = new byte[1024];
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {
               while(!Thread.currentThread().isInterrupted() && !stopWorker)
               {
                    try
                    {
                        int bytesAvailable = mmInputStream.available();
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
                            for(int i=0;i<bytesAvailable;i++)
                            {
                                byte b = packetBytes[i];
                                if(b == delimiter)
                                {
                                    byte[] encodedBytes = new byte[readBufferPosition];
                                    System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                                    final String data = new String(encodedBytes, "US-ASCII");
                                    readBufferPosition = 0;

                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                            myLabel.setText(data);
                                        }
                                    });
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }
                        }
                    }
                    catch (IOException ex)
                    {
                        stopWorker = true;
                    }
               }
            }
        });

        workerThread.start();
    }


如果有所作为,则数据来自Arudino,我可以修改其流式传输方式。

谢谢!

最佳答案

使用包裹在DataInputStream周围的BufferedInputStreamreadInt()方法。当然,这假定网络字节顺序为整数。

忘记所有这些arraycopy()的东西。

08-16 22:35