当你成功地连接了两台(或多台)设备时,每个设备都有一个已连接的BluetoothSocket。这时你可以在设备之间共享数据,乐趣才刚开始。 使用BluetoothSocket,传输二进制数据的过程是简单的:
- 分别通过getInputStream()和getOutputStream()获得管理数据传输的InputStream和OutputStream。
- 通过read(byte[])和write(byte[])从流中读取或写入数据。
首先,你必须使用一个线程专门用于数据的读或写。这是非常重要的,因为read(byte[])和write(byte[])方法都是阻塞调用。read(byte[])将会阻塞到流中有数据可读。write(byte[])一般不会阻塞,但当远程设备的中间缓冲区已满而对方没有及时地调用read(byte[])时将会一直阻塞。所以,你的线程中的主循环将一直用于从InputStream中读取数据。 A separate public method in the thread can be used to initiate writes to theOutputStream
.
Example
- 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) { }
- }}