Android的蓝牙接口教程非阻塞通信 [英] Android Bluetooth socket tutorial for non-blocking communication

查看:212
本文介绍了Android的蓝牙接口教程非阻塞通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要寻找一个蓝牙样品code在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...

非常感谢你。

推荐答案

貌似答案是pretty的多,你不能

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的蓝牙接口教程非阻塞通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆