来自蓝牙的Android流媒体缓冲读卡器

时间:2015-08-10 07:11:34

标签: java android bluetooth stream arduino

嘿伙计们,所以我试图从蓝牙设备中读取连续流整数的流:

-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,我可以修改它的流式传输方式。

谢谢!

1 个答案:

答案 0 :(得分:0)

使用DataInputStream BufferedInputStreamreadInt()方法。这假设网络字节顺序当然是整数。

忘记所有这些arraycopy()内容。