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.

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. android 加载已经安装的apk方式
  2. 【Android】Menu不同菜单的使用介绍
  3. 如何在Android平台上创建自定义的Cordova
  4. android 隐藏键盘 显示键盘
  5. android4.4系统永不锁屏
  6. Android常用mimetype类型
  7. android 层叠图片形成一张图片
  8. uiautomator2(用python控制android), 安装
  9. Android(安卓)判断当前网络 wifi ctwap(c
  10. [转]Android(安卓)Opengl - Colored 3D C