android - 蓝牙 : program stuck at inputstream reading

标签 android bluetooth inputstream

你好。

我正在开发一个通过蓝牙传输数据的应用程序(使用飞行记录器设备)。当我接收大量数据(3000 - 40000 行文本,取决于文件大小)时,我的应用程序似乎停止接收数据。我使用 InputStream.read(buffer) 接收数据。例如:我向飞行记录器发送一个命令,它开始向我发送一个文件(逐行),在我的手机上我收到 120 行,然后应用程序卡住了。

有趣的是,在我的 HTC Desire 上,应用程序有时会卡住,而在三星 Galaxy S 手机上,每次我尝试接收超过 50 条线路时,应用程序都会卡住。

该代码基于BluetoothChat 示例。这是我正在监听蓝牙套接字的代码部分:

byte[] buffer = new byte[1024];
int bytes =0;

while(true)
{
    bytes = mmInStream.read(buffer); 
    readMessage = new String(buffer, 0, bytes);
    Log.e("read", readMessage);

    String read2 = readMessage;
    //searching for the end of line to count the lines(the star means the start of the checksum)
    int currentHits = read2.replaceAll("[^*]","").length(); 
    nmbrOfTransferedFligts += currentHits;
    .
    .
    .
    //parsing and saving the recieved data         

我必须说我在一个线程中的 while(true) 循环中运行它,该线程是在 android 服务中实现的。该应用程序似乎停留在“bytes = mmInStream.read(buffer);” 我尝试使用 BufferedReader 执行此操作,但没有成功。

谢谢。

最佳答案

The app seems to stuck at "bytes = mmInStream.read(buffer);"

但这是正常行为:当没有更多可用数据时,InputStream.read(byte[]) 会阻塞。

这表明问题出在另一端或设备之间的通信上。您是否可能遇到通信问题(Galaxy 与 Desire 上的情况略有不同),导致无法接收更多数据?

此外,我建议您在读取语句周围使用 try/catch 以确保捕获任何可能的 IOException。不过我猜如果发生这种情况,您会在 logcat 中看到它。

说到 logcat,我建议您查看 Android 本身生成的 logcat 语句。我发现它为蓝牙生成了很多数据,这可能会帮助您确定是否确实还有更多数据需要读取()。

关于android - 蓝牙 : program stuck at inputstream reading,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9877990/

相关文章:

使用 xerces 进行 Android 模式验证

python - 是否有适用于 Windows 7 64 位的 Python 蓝牙模块?

java - 当我们写入 OutputStream 时,我们不应该跟踪偏移量吗?

javascript - 来自 JavaScript Websocket 的 InputStream Java 未收到完整消息

android - 如何使用 achartengine 在 fragment 中膨胀 Intent

android - 即使数据存在于数据库中,也无法从 sqlite 数据库检索数据

android - 将附件/属性移动到新信标

linux - Bluez-5.36 StartDiscovery() 方法

java - 如何通过蓝牙通过多部手机传输音乐

java - 我可以关闭/重新打开 InputStream 来模拟不支持标记的输入流的标记/重置吗?