gpt4 book ai didi

android - Xamarin Bluetooth InputStream 不读取所有字节(有时)

转载 作者:搜寻专家 更新时间:2023-11-01 08:37:20 27 4
gpt4 key购买 nike

我使用此代码读取蓝牙非 LE 设备的回复。

解决方案是一个 Xamarin Forms 项目,代码在 DependencyService 中。

using Android.Bluetooth;

....

public byte[] GetCommand()
{
byte[] rbuffer = new byte[200];
try
{

// Read data from the device
while (!_socket.InputStream.CanRead || !_socket.InputStream.IsDataAvailable())
{

}
int readByte = _socket.InputStream.Read(rbuffer, 0, rbuffer.Length);

}
catch (Java.IO.IOException e)
{

}
return rbuffer;
}

怎么可能解决呢?

最佳答案

我会改用下面的代码:

//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;


//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;

try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }

mmInStream = tmpIn;
mmOutStream = tmpOut;
}

public void run() {
byte[] buffer = new byte[256];
int bytes;

// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();

}
}
}

这对我来说很有效,可以从 Arduino 获取蓝牙信息! :)

关于android - Xamarin Bluetooth InputStream 不读取所有字节(有时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35718125/

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