你好。
我正在开发一个通过蓝牙传输数据的应用程序(使用飞行记录器设备)。当我接收大量数据(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/