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

时间:2011-11-20 20:04:26

标签: android sockets asynchronous bluetooth

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

我找到了几个例子,比如BluetoothChat或BluetoothSocket.java但没有non-blocking socket communication.

ps非阻塞自动意味着必须是异步的吗?我认为其实不是 - 它不一样,我假设我可以通过超时进行同步套接字通信。这就是我要找的那种例子......

非常感谢

1 个答案:

答案 0 :(得分:11)

看起来答案几乎是你不能

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

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