gpt4 book ai didi

android - 蓝牙聊天不工作

转载 作者:行者123 更新时间:2023-11-29 02:16:54 24 4
gpt4 key购买 nike

您好,我想在 Android 设备之间进行对话。我使用 BluetoothChat 来执行此操作,但它不起作用我无法从另一台设备正确读取数据。

对话是:

我:女贞

设备:p装置:铆钉

你能帮帮我吗?

私有(private)类 ConnectedThread 扩展线程 {

    private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
//InputStream tmpIn = null;
OutputStream tmpOut = null;
BufferedInputStream tmpIn=null;

int INPUT_BUFFER_SIZE=32;
// Get the BluetoothSocket input and output streams
try {
//tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
tmpIn = new BufferedInputStream(socket.getInputStream(),INPUT_BUFFER_SIZE);

} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}

mmInStream = tmpIn;
mmOutStream = tmpOut;
}

public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;

// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream

bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}

最佳答案

解决方案的修复是在连接的线程中创建字符串,直接在 InputStream 上调用 read() 之后,然后将字符串传递回主线程以供显示。无论出于何种原因,在线程之间传递字节数组会导致大量重复和数据丢失。

修改后的 run() 代码:

public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()

// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, readMessage)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}

处理程序接收:

case MESSAGE_READ:
// Read in string from message, display to mainText for user
String readMessage = (String) msg.obj;
if (msg.arg1 > 0) {
mainText.append(readMessage);
}

关于android - 蓝牙聊天不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3063295/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com