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 ...
随机推荐
- springboot08 jdbc
一.JDBC&连接池 1. jdbc介绍 JDBC(Java DataBase Connectivity ,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数 ...
- shell之ip命令
转:出处我也不知道了,学习时候记下的笔记 1.作用 ip是iproute2软件包里面的一个强大的网络配置工具,它能够替代一些传统的网络管理工具,例如ifconfig.route等,使用权限为超级用户. ...
- shell之一些测试脚本
比较文件有无修改,通过修改时间判别 # !/bin/bash dir=$ for file in `ls $dir` do if [ -d $dir/$file ] then echo $file i ...
- Spring框架jar包分类(转)
转自:http://www.cnblogs.com/JSONBEAN/p/6364038.html 长期以来都在写SSM框架的项目,却未能深入理解框架的搭建原理,而只是浅薄的理解前辈的架构,然后不断套 ...
- Codeforces Round #418 (Div. 2) D. An overnight dance in discotheque
Codeforces Round #418 (Div. 2) D. An overnight dance in discotheque 题意: 给\(n(n <= 1000)\)个圆,圆与圆之间 ...
- ClientScript.RegisterClientScriptBlock 不执行
ClientScript.RegisterClientScriptBlock 不执行 页面中 form标签必须加入 runat=server
- request.getScheme()的使用方法
今天在修改bug时,发现程序使用了 request.getScheme() .不明白是什么意思,在google 搜索了一下.现在明白了.整理如下: 1.request.getScheme() 返回当前 ...
- 谈谈dpdk应用层包处理程序的多进程和多线程模型选择时的若干考虑
看到知乎上有个关于linux多进程.多线程的讨论:http://www.zhihu.com/question/19903801/answer/14842584 自己项目里也对这个问题有过很多探讨和测试 ...
- 小知识:SPI四种模式区别【转】
转自:http://home.eeworld.com.cn/my/space-uid-80086-blogid-119198.html spi四种模式SPI的相位(CPHA)和极性(CPOL)分别可以 ...
- ajax验证前端页面
1.html页面 用ajax验证表单的时候不需要form标签,并把提交按钮由type=“submit ”改为type=“button” 数据表结构 ajax.html <!DOCTYPE htm ...