我有以下代码,我试图将收到的字节保存到字符串,直到我收到\ n。
byte[] buffer = new byte[1024];
int bytes;
String ReceivedMessage = null;
while (true) {
try
{
// Read from the InputStream
bytes = mmInStream.read(buffer);
ReceivedMessage = ReceivedMessage + getString(bytes);
// Send the obtained bytes to the UI Activity
if(ReceivedMessage.endsWith("\\n")) {
String StringToReturn = ReceivedMessage.replace("\\n","");
Message msg = mHandler.obtainMessage(AbstractActivity.MESSAGE_READ);
Bundle bundle = new Bundle();
bundle.putString("Message", StringToReturn);
msg.setData(bundle);
mHandler.sendMessage(msg);
//mHandler.obtainMessage(AbstractActivity.MESSAGE_READ, bytes, -1, buffer)
// .sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
connectionLost();
BluetoothService.this.stop();
break;
}
问题是它在ReceivedMessage = ReceivedMessage + getString(bytes);
上崩溃,更确切地说是getString(bytes)
你能帮我解决一下吗?
谢谢!
答案 0 :(得分:0)
编辑此内容,因为我无法发表评论:
你只能读一次缓冲区
bytes = mmInStream.read(buffer);
如果确实它是相同的缓冲区,则读取内容。很难说。
while(true)
也意味着这最终会触发异常。
[编辑]
堆栈跟踪是什么? getString调用了什么?你为什么使用"而(true)"没有任何出路?您是否试图从StreamBuffer中读取两次?
(这将是一个评论,但没有足够的代表)
答案 1 :(得分:0)
String TempString = new String(buffer,0,bytes);
ReceivedMessage = ReceivedMessage + TempString;