我正在尝试使用 Android 的 BlueToothChat 示例,但有些东西我不明白:
byte[] send = message.getBytes();
Log.d("SEND_BYTE", send.toString());
mChatService.write(send);
这里,消息是一个字符串,然后将其转换为字节,我猜是为了发送。但是当我检查日志时,即使我输入的消息很长,send.toString()
部分也非常短。更糟糕的是,如果我输入两次相同的消息,我会得到两个不同的日志,我觉得这真的很奇怪。
以下是我在日志中连续三次收到消息 hello
的内容:
[B@413d62e0
[B@41390078
[B@413ed3d8
一定有一些东西(也许很简单)我没有得到,但无法弄清楚它是什么。你能帮我吗?
编辑: 也许添加以下代码很有用,所以这里是完整的代码:
byte[] send = message.getBytes();
Log.d("SEND_BYTE", send.toString());
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field (buffer is used in the write function)
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
最佳答案
是的,在字节数组上调用toString()
是一个坏主意。数组不会覆盖 toString()
,因此您会获得 Object.toString()
的默认行为。
要反转 String.getBytes()
调用,您需要:
Log.d("SEND_BYTE", new String(send));
或者更直接地查看字节:
Log.d("SEND_BYTE", Arrays.toString(send));
但是,我强烈建议您不要直接这样做。相反,您应该在与二进制转换时指定编码,否则它将使用平台默认编码。聊天服务需要什么编码?例如,如果需要 UTF-8:
byte[] send = message.getBytes("UTF-8");
Log.d("SEND_BYTE", Arrays.toString(send));
mChatService.write(send);
关于java - getBytes 然后 toString 每次都不会给出相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15407201/