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.

Android Developer -- Bluetooth篇 开发实例之三 管理连接的更多相关文章

  1. Android Developer -- Bluetooth篇 开发实例之四 API详解

    http://www.open-open.com/lib/view/open1390879771695.html 这篇文章将会详细解析BluetoothAdapter的详细api, 包括隐藏方法, 每 ...

  2. Android Developer -- Bluetooth篇 开发实例之一 扫描设备

    第一步:声明Bluetooth Permissions <!-- 设置蓝牙访问权限 --> <uses-permission android:name="android.p ...

  3. Android Developer -- Bluetooth篇 开发实例之二 连接设备

    连接设备 In order to create a connection between your application on two devices, you must implement bot ...

  4. Bluetooth篇 开发实例之九 和蓝牙模块通信

    首先,我们要去连接蓝牙模块,那么,我们只要写客户端的程序就好了,蓝牙模块就相当于服务端. 连接就需要UUID. #蓝牙串口服务SerialPortServiceClass_UUID = ‘{00001 ...

  5. Bluetooth篇 开发实例之八 匹配

    自己写的App匹配蓝牙设备,不需要通过系统设置去连接. 匹配和通信是两回事. 用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK ...

  6. Bluetooth篇 开发实例之七 匹配&UUID

    匹配和通信是两回事. 1.用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK中给出.但是可以通过反射来获取. 知道这两个API的 ...

  7. Android Developer -- Bluetooth篇 概述

    Bluetooth 安卓平台支持蓝牙网络协议栈,它允许设备与其他蓝牙设备进行无线交换数据.应用程序框架通过安卓蓝牙APIs提供访问蓝牙功能.这些APIs使应用程序通过无线连接到其他蓝牙设备,使点对点和 ...

  8. Bluetooth篇 开发实例之十 官网的Bluetooth Chat sample app.

    运行的时候,会报错: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Action ...

  9. Bluetooth篇 开发实例之十一 官网的Bluetooth Chat sample的bug

    当没有匹配的设备和没有找到可用设备的时候. // If there are paired devices, add each one to the ArrayAdapter if (pairedDev ...

随机推荐

  1. HDU 4189 Cybercrime Donut Investigation 线段树+思路

    参考:http://www.cnblogs.com/slon/archive/2012/03/30/2426104.html 题意:给一个有n个点的点集,有q个询问,每个询问询问一个点p,求与p曼哈顿 ...

  2. Android动态添加和移除布局

    package com.hyang.administrator.studentproject; import android.os.Bundle; import android.support.v7. ...

  3. event.returnValue=false与event.preventDefault()

    event.preventDefault()方法是用于取消事件的默认行为,但此方法并不被ie支持,在ie下需要用window.event.returnValue = false; 来实现. funct ...

  4. 团队Alpha版本冲刺(四)

    目录 组员情况 组员1(组长):胡绪佩 组员2:胡青元 组员3:庄卉 组员4:家灿 组员5:凯琳 组员6:丹丹 组员7:何家伟 组员8:政演 组员9:鸿杰 组员10:刘一好 组员:何宇恒 展示组内最新 ...

  5. RabbitMQ磁盘警报

    RabbitMQ磁盘警报 当可用磁盘空间低于配置的限制(默认为50MB)时,将触发警报,所有生产者将被阻止.目标是避免填满整个磁盘,这将导致节点上的所有写操作失败,并可能导致RabbitMQ终止.为了 ...

  6. 【bzoj1007】[HNOI2008]水平可见直线 半平面交/单调栈

    题目描述 在xoy直角坐标平面上有n条直线L1,L2,...Ln,若在y值为正无穷大处往下看,能见到Li的某个子线段,则称Li为可见的,否则Li为被覆盖的.例如,对于直线:L1:y=x; L2:y=- ...

  7. 【HDU 3336 Count the string】

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submission( ...

  8. 如何设置两个AD域控制器

    目的:这要为了测试,哈哈哈哈. 其实是为了AD域控的高可用性.一个域控down了,另一个可以顶上去. 如何设置:参考http://lgzeng2360.blog.51cto.com/275998/10 ...

  9. Codeforces Round #324 (Div. 2) A

    A. Olesya and Rodion time limit per test 1 second memory limit per test 256 megabytes input standard ...

  10. hadoop学习之HDFS

    1.什么是大数据?什么是云计算?什么是hadoop? 大数据现在很火,到底什么是大数据,多大的数据才算大,一般而言对于TB级以上的数据我们成为大数据,对于这些数据它的价值在哪?大数据的价值就是我们大量 ...