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:
- Get the
InputStreamandOutputStreamthat handle transmissions through the socket, viagetInputStream()andgetOutputStream(), respectively. - Read and write data to the streams with
read(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 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篇 开发实例之三 管理连接的更多相关文章
- Android Developer -- Bluetooth篇 开发实例之四 API详解
http://www.open-open.com/lib/view/open1390879771695.html 这篇文章将会详细解析BluetoothAdapter的详细api, 包括隐藏方法, 每 ...
- Android Developer -- Bluetooth篇 开发实例之一 扫描设备
第一步:声明Bluetooth Permissions <!-- 设置蓝牙访问权限 --> <uses-permission android:name="android.p ...
- Android Developer -- Bluetooth篇 开发实例之二 连接设备
连接设备 In order to create a connection between your application on two devices, you must implement bot ...
- Bluetooth篇 开发实例之九 和蓝牙模块通信
首先,我们要去连接蓝牙模块,那么,我们只要写客户端的程序就好了,蓝牙模块就相当于服务端. 连接就需要UUID. #蓝牙串口服务SerialPortServiceClass_UUID = ‘{00001 ...
- Bluetooth篇 开发实例之八 匹配
自己写的App匹配蓝牙设备,不需要通过系统设置去连接. 匹配和通信是两回事. 用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK ...
- Bluetooth篇 开发实例之七 匹配&UUID
匹配和通信是两回事. 1.用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK中给出.但是可以通过反射来获取. 知道这两个API的 ...
- Android Developer -- Bluetooth篇 概述
Bluetooth 安卓平台支持蓝牙网络协议栈,它允许设备与其他蓝牙设备进行无线交换数据.应用程序框架通过安卓蓝牙APIs提供访问蓝牙功能.这些APIs使应用程序通过无线连接到其他蓝牙设备,使点对点和 ...
- Bluetooth篇 开发实例之十 官网的Bluetooth Chat sample app.
运行的时候,会报错: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Action ...
- Bluetooth篇 开发实例之十一 官网的Bluetooth Chat sample的bug
当没有匹配的设备和没有找到可用设备的时候. // If there are paired devices, add each one to the ArrayAdapter if (pairedDev ...
随机推荐
- winform 路径
System.AppDomain.CurrentDomain.BaseDirectory d:\project\bin\release\
- HDU 4474 Yet Another Multiple Problem ( BFS + 同余剪枝 )
没什么巧办法,直接搜就行. 用余数作为每个节点的哈希值. #include <cstdio> #include <cstring> #include <cstdlib&g ...
- Struts2+DAO层实现实例03——添加监听器跟踪用户行为
实例说明 根据上两次的成品进行二次加工. 加入Listener,监听用户的登陆注销情况. 所用知识说明 采用SessionBindingListener对Session进行监听. 同时,Action中 ...
- objective-c runtime 开发详情
目录 概述 对象与类的实质 id与class 继承关系与isa 总结 C函数创建一个OC类 OC类与runtime NSObjectProtocol NSObject NSProxy 一.概述 Obj ...
- asp.net 条码 一维条码 生成, 一共有32中格式类型
想用asp.net 实现条码功能,网上找了代码都不全. 终于找到了一个非常全的DLL 是winForm的,原以为不能用在WEB 上结果 可以使用. 首先,引用 DLL 不必说了,下面是 使用设置.还有 ...
- [洛谷P2613]【模板】有理数取余
题目大意:给你$a,b(a,b\leqslant10^{10001})$,求出$\dfrac a b\equiv1\pmod{19260817}$,无解输出 Angry! 题解:在读入的时候取模,若$ ...
- [bzoj3218] a+b problem [最小割+数据结构优化建图]
题面 传送门 思路 最小割 我们首先忽略掉那个奇♂怪的限制,就有一个比较显然的最小割模型: 建立源点$S$和汇点$T$ 对于每个元素$i$建立一个点$i$,连边$<S,i,w[i]>$和$ ...
- Vue组件中的单项数据流
当子组件中的input v-model 父组件的值时不能直接绑定props的值要使用计算属性,向下面的写法,因为props是单项数据流,子组件不能改变父组件的状态,直接绑定会报错. 还可以这样写:但是 ...
- js函数调用与声明 (for时注意)
可以的: test(); // 直接function 方式声明的函数可以直接调用,后声明 function test(){} aa(); //error var 方式声明的函数需先声明后调用v ...
- HTML中打开新页面的方法
HTML跳转新窗口的方法 笔试遇到这样的一个问题,特意整理一下. 方法一 纯HTML <a href="http://www.cnblogs.com" target=&quo ...