• Android Developer -- Bluetooth篇 开发实例之三 管理连接


    Managing a Connection

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

    1. Get the InputStream and OutputStream that handle transmissions through the socket, via getInputStream() and getOutputStream(), respectively.
    2. Read and write data to the streams with read(byte[]) and write(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 both read(byte[]) and write(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 calling read(byte[]) quickly enough and the intermediate buffers are full. So, your main loop in the thread should be dedicated to reading from the InputStream. A separate public method in the thread can be used to initiate writes to the OutputStream.

    当你成功的连接到两个(或者更多)设备的时候,每一个都会拥有一个连接的BluetoothSocket. 这样,你就可以分享数据了。使用 BluetoothSocket,交换任意数据的过程:

    第一步:

    1.通过 socket,使用getInputStream() and getOutputStream(),来获取 InputStream and OutputStream去处理信息。

    第二步:

    2.通过read(byte[]) and write(byte[]).来从流中读写数据。

    没了。

    当然要考虑执行的细节。第一步,也是最重要的步骤,就是创建一个专门处理所有流读写的线程。这是非常重要的额,因为 read(byte[]) and write(byte[]) methods

    是阻塞的方法。 read(byte[])方法总是会阻塞直到能从流中读取到数据。write(byte[]) 不总是阻塞,但会阻塞流控制,如果远程设备没有及时用read(byte[]) 方法使得中间缓冲区满了。所以,该线程中的主回路应致力于从输入流读取。另外暴露一个公共方法可以用来启动写入输出流。

    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. When read(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's write() 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's cancel() method is important so that the connection can be terminated at any time by closing the BluetoothSocket. This should always be called when you're done using the Bluetooth connection.

    构造器会获得必要的流,而且这个线程一旦被启动,这个线程通过InputStream等待数据。当read(byte[])会从这个流中返回bytes,数据会被送到mian aty,通过使用父类的成员变量Handler。然后,它会返回这个流中并等待更多的bytes。

    发送数据,只要在main aty中简单的调用线程的 write()方法即可。这个方法会发送数据给远程设备。

    这个线程的cancel()方法也是很重要的。它可以通过关闭BluetoothSocket.来结束连接。它总是被调用,如果你通过蓝牙连接完成了你的事情。

    For a demonstration of using the Bluetooth APIs, see the Bluetooth Chat sample app.

  • 相关阅读:
    cppPrimer学习18th
    cppPrimer学习17th
    cppPrimer学习15th
    常用网站记录
    cppPrimer学习16th
    关于nfs内网穿透frp/nps的问题记录
    unp[unix 网络环境编程]学习 vscode环境搭建
    cppPrimer学习14th
    cppPrimer学习14th
    cppPrimer学习13th
  • 原文地址:https://www.cnblogs.com/H-BolinBlog/p/5542109.html
Copyright © 2020-2023  润新知