Android蓝牙socket非阻塞通信教程 [英] Android Bluetooth socket tutorial for non-blocking communication
问题描述
我正在寻找 Android 上的蓝牙示例代码来进行非阻塞套接字通信.
I am looking for a bluetooth sample code on Android to do non-blocking socket communication.
我发现了几个例子,比如 BluetoothChat 或 BluetoothSocket.java,但没有一个是非阻塞套接字通信.
I found several examples, like the BluetoothChat or BluetoothSocket.java but none is non-blocking socket communication.
ps 非阻塞是否自动意味着必须是异步的?我认为实际上不是 - 它不一样,我假设我可以在超时的情况下进行同步套接字通信.这就是我正在寻找的那种例子......
ps does non-blocking automatically mean that is has to be asynchronous? I think actually not - it is not the same, I assume I could do synchronous socket communication with a timeout. That's the kind of example I am looking for...
非常感谢
推荐答案
看起来答案几乎是你不能
Looks like the answer is pretty much you can't
但是通过一些线程魔法,您可以让您的系统按照您想要的方式工作
however with a bit of threading magic, your can have your system work the way you want
BluetoothSocketListener bsl = new BluetoothSocketListener(socket, handler, messageText);
Thread messageListener = new Thread(bsl);
messageListener.start();
消息系统
private class MessagePoster implements Runnable {
private TextView textView;
private String message;
public MessagePoster(TextView textView, String message) {
this.textView = textView;
this.message = message;
}
public void run() {
textView.setText(message);
}
}
套接字监听器
private class BluetoothSocketListener implements Runnable {
private BluetoothSocket socket;
private TextView textView;
private Handler handler;
public BluetoothSocketListener(BluetoothSocket socket,
Handler handler, TextView textView) {
this.socket = socket;
this.textView = textView;
this.handler = handler;
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
try {
InputStream instream = socket.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead==bufferSize)&&(buffer[bufferSize-1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead - 1);
handler.post(new MessagePoster(textView, message));
socket.getInputStream();
}
}
} catch (IOException e) {
Log.d("BLUETOOTH_COMMS", e.getMessage());
}
}
}
这篇关于Android蓝牙socket非阻塞通信教程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!