【问题标题】:My bluetooth connexion is reading only zeros我的蓝牙连接只读取零
【发布时间】:2012-03-21 17:19:19
【问题描述】:

我正在尝试从我的 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 个字节。知道我为什么会得到这个吗?

【问题讨论】:

  • GPS 是什么品牌和型号?
  • 这是一个 u-blox LEA-4T GPS 芯片集成。我们已经将它安装到一个可以通过蓝牙或 USB 输出日志的盒子中。当我将盒子连接到我的电脑(通过 USB)时,我可以完美地看到 NMEA 字符串。此外,我们在 PDA 上广泛使用 Windows Mobile 程序的蓝牙连接,因此硬件集成应该不是问题。我想知道什么可以让程序读取 0 和 -32 字节...

标签: android bluetooth inputstream


【解决方案1】:
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(byte[]),其中byte[] 是不推荐使用byte[] 大小的缓冲区。我已经使用过很多次了,即使缓冲区大小随时间而变化,它也对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 2016-12-13
    相关资源
    最近更新 更多