Android蓝牙SPP - 发送/接收数据

时间:2015-06-23 01:37:18

标签: android bluetooth serial-port

我正在创建一个Android应用程序,我需要连接经典蓝牙设备(不是BLE)。

我的规格说我需要向串口写入一些字节来发送命令才能启动...当我收到它开始的答案时,我可以发送另一个字节数组来请求设备的答案。

是否有任何示例代码我可以咨询从我的设备获取数据?

目前我打开了与SPP UUID服务的连接并发送了字节,但我没有得到任何答案。该设备绝对有效,因为我可以用另一个应用程序测试它。

我的代码中的一些代码段: (设备不为空且已连接)

    UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
    //UUID uuid = UUID.fromString("00005500-D102-11E1-9B23-00025B00A5A5");
    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
    mmSocket.connect();
    mmOutputStream = mmSocket.getOutputStream();
    mmInputStream = mmSocket.getInputStream();
    listenForData();



void sendData(byte[] bytes) throws IOException
{
    mmOutputStream.write(bytes);
    Log.d(AppConstants.APP_TAG, "Data Sent");
}


void listenForData()
{
    final Handler handler = new Handler();
    final byte delimiter = 55; //not sure about this yet

    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)
                    {
                        Log.d(AppConstants.APP_TAG, "Found DATA!!!!");
                        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()
                                    {
                                        Log.d(APP_TAG, data);
                                    }
                                });
                            }
                            else
                            {
                                readBuffer[readBufferPosition++] = b;
                            }
                        }
                    }
                }
                catch (IOException ex)
                {
                    stopWorker = true;
                }
            }

        }
    });

    workerThread.start();
}

有什么建议吗?

0 个答案:

没有答案