Android蓝牙套接字教程,用于无阻塞通信

我正在寻找Android上的蓝牙示例代码来做非阻塞套接字通信。

我发现了几个例子,像BluetoothChat或BluetoothSocket.java,但没有一个是non-blocking socket communication.

ps做非阻塞自动意味着必须是asynchronous的? 我想实际上不是 – 这是不一样的,我认为我可以做超时同步套接字通信。 这是我正在寻找的那种例子…

非常感谢你

看起来答案几乎是你不能的

然而有了一些线程魔法,你可以让你的系统按你想要的方式工作

  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()); } } }