如何从蓝牙设备读取到Android应用程序。

时间:2017-02-10 03:17:14

标签: android bluetooth inputstream bufferedreader

我正在尝试从连接到arduino的HC-06蓝牙模块读取测试。我知道他们有联系。我发送文本到arduino,作为回报它做了一些事情,但后来我想从arduino读取Serial.print(“something”)。我从bytesAvailable得到一个大于0的值,但我似乎无法弄清楚如何实际读取它所以我可以在某处打印它。有什么想法吗?

它将所有日志打印到Log.e(“连接”,“BEFORE WHILE”);但是当它尝试读取缓冲区读取器时似乎卡住但是它不会给我一个错误来解决问题

    private void fromArduino()
            {
                if (btSocket!=null)
                {
                    try
                    {
                        inStream = btSocket.getInputStream();

                        int bytesAvailable = inStream.available();
                    Log.e("Connection",String.valueOf(bytesAvailable));

                    if(bytesAvailable > 0)
                    {
                        while(true) {
                            Log.e("Connection", "IN IF STATE");
                            byte[] packetBytes = new byte[bytesAvailable];
                            readBufferPosition = inStream.read(packetBytes);
                            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inStream, "US-ASCII"));
                            Result = "";
                            String line = "";
                            Log.e("Connection", "BEFORE WHILE");
                            line = bufferedReader.readLine();
                            Log.e("Connection", line);
                        /*while ((line=bufferedReader.readLine())!=null){
                            Log.e("Connection",line);
                            Result+=line;
                        }*/
                            bufferedReader.close();
                            inStream.close();
                            Log.e("Connection", "FINISH");
                        }
                        /*for(int i=0;i<bytesAvailable;i++)
                        {
                            byte b = packetBytes[i];

                            byte[] encodedBytes = new byte[readBufferPosition];
                            System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
                            final String data = new String(encodedBytes, "US-ASCII");
                            readBufferPosition = 0;
                        }*/
                    }
                }
                catch (IOException e)
                {

                }
            }
        }

0 个答案:

没有答案