我的蓝牙连接只读零

时间:2012-03-03 12:49:25

标签: android bluetooth inputstream

在我的Android手机中,我试图通过外部GPS设备读取(使用蓝牙)字符串。我主要关注的是BluetoothChat示例,到目前为止,一切似乎都按预期工作。我的读取线程正在执行,我可以看到使用以下代码循环时传入的可变字节数据包:

Log.d(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) 
{
    try 
    {                   
        bytes = mmInStream.read(buffer);

        // Test...
        String strReadBuf = new String(buffer, 0, bytes);   

       // Send the obtained bytes to the UI Activity
       mHandler.obtainMessage(BluetoothHandler.MessageType.READ,
            bytes, buffer).sendToTarget();
    } catch (IOException e) {
         Log.e(TAG, "disconnected", e);
         sendErrorMessage(R.string.bt_connection_lost);
         break;
    }
 }

我应该读取的字符串是文本字符串(NMEA格式),但我在缓冲区数组中只读取0和-32字节。知道我为什么会这样做吗?

1 个答案:

答案 0 :(得分:0)

Log.d(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true)
{
    try
    {
        bytes = mmInStream.read(buffer);

        // Test...
        //String strReadBuf = new String(buffer, 0, bytes);
        //I've changed for
        String strReadBuf = new String(buffer);


       // Send the obtained bytes to the UI Activity
       mHandler.obtainMessage(BluetoothHandler.MessageType.READ,
            bytes, buffer).sendToTarget();
    } catch (IOException e) {
         Log.e(TAG, "disconnected", e);
         sendErrorMessage(R.string.bt_connection_lost);
         break;
    }
 }

我使用了String构造函数String(byte[]),其中byte[]是不推荐使用byte[]大小的缓冲区。我已经使用了很多次,即使缓冲区大小随时间变化也适用于我。