android bluetooth开发基础-7管理连接

Managing a Connection

When you have successfully connected two (or more) devices, each one will have a connectedBluetoothSocket. This is where the fun begins because you can share data between devices. Using theBluetoothSocket, the general procedure to transfer arbitrary data is simple:

  1. Get theInputStreamandOutputStreamthat handle transmissions through the socket, viagetInputStream()andgetOutputStream(), respectively.
  2. Read and write data to the streams withread(byte[])andwrite(byte[]).

That's it.

There are, of course, implementation details to consider. First and foremost, you should use a dedicated thread for all stream reading and writing. This is important because bothread(byte[])andwrite(byte[])methods are blocking calls.read(byte[])will block until there is something to read from the stream.write(byte[])does not usually block, but can block for flow control if the remote device is not callingread(byte[])quickly enough and the intermediate buffers are full. So, your main loop in the thread should be dedicated to reading from theInputStream. A separate public method in the thread can be used to initiate writes to theOutputStream.

Example

Here's an example of how this might look:

private class ConnectedThread extends Thread {
  private final BluetoothSocket mmSocket;
  private final InputStream mmInStream;
  private final OutputStream mmOutStream;

  public ConnectedThread(BluetoothSocket socket) {
    mmSocket = socket;
    InputStream tmpIn = null;
    OutputStream tmpOut = null;

    // Get the input and output streams, using temp objects because
    // member streams are final
    try {
      tmpIn = socket.getInputStream();
      tmpOut = socket.getOutputStream();
    } catch (IOException e) { }

    mmInStream = tmpIn;
    mmOutStream = tmpOut;
  }

  public void run() {
    byte[] buffer = new byte[1024]; // buffer store for the stream
    int bytes; // bytes returned from read()

    // Keep listening to the InputStream until an exception occurs
    while (true) {
      try {
        // Read from the InputStream
        bytes = mmInStream.read(buffer);
        // Send the obtained bytes to the UI Activity
        mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
            .sendToTarget();
      } catch (IOException e) {
        break;
      }
    }
  }

  /* Call this from the main Activity to send data to the remote device */
  public void write(byte[] bytes) {
    try {
      mmOutStream.write(bytes);
    } catch (IOException e) { }
  }

  /* Call this from the main Activity to shutdown the connection */
  public void cancel() {
    try {
      mmSocket.close();
    } catch (IOException e) { }
  }
}

The constructor acquires the necessary streams and once executed, the thread will wait for data to come through the InputStream. Whenread(byte[])returns with bytes from the stream, the data is sent to the main Activity using a member Handler from the parent class. Then it goes back and waits for more bytes from the stream.

Sending outgoing data is as simple as calling the thread'swrite()method from the main Activity and passing in the bytes to be sent. This method then simply callswrite(byte[])to send the data to the remote device.

The thread'scancel()method is important so that the connection can be terminated at any time by closing theBluetoothSocket. This should always be called when you're done using the Bluetooth connection.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值