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
InputStream
andOutputStream
that 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 ...
随机推荐
- 2 27re.py
""" 匹配目标 """ # import re # content = 'Hello 123 4567 World_This is a R ...
- 解决windows文件名过长无法删除的问题
删除windows文件时,系统提示如下错误: 从网上找到下面的一种方法,顺利解决(原理不清楚),现记录删除方法如下: . 在要删除的文件夹(delete_dir)同级新建一个空文件夹(empty_di ...
- python 读取consul配置
自动化通过rcp client调用远端服务接口时,都需要将远端测试服务ip.端口记录在配置文件. 但由于,服务发布或重启会导致ip.端口变动. 以下将通过python-consul 自动去读取cons ...
- kvm竟然抓不到kvm的tracepoint
今天终于把kvm给搭起来了,打开了host机的tracepoint竟然一个都没有抓到,这是咋回事? 难道kvm的东西只有在启动的时候才会被抓到? 虚拟出来一块内存一块CPU,虚拟出来一个内存.感觉都好 ...
- Manacher算法学习 【马拉车】
好久没写算法学习博客了 比较懒,一直在刷水题 今天学一个用于回文串计算问题manacher算法[马拉车] 回文串 回文串:指的是以字符串中心为轴,两边字符关于该轴对称的字符串 ——例如abaaba 最 ...
- 《c程序设计语言》读书笔记-递归实现快速排序算法
#include <stdio.h> void swap(int v[],int i,int j) { int temp; temp = v[i]; v[i] = v[j]; v[j] = ...
- Codeforces 938.B Run For Your Prize
B. Run For Your Prize time limit per test 1 second memory limit per test 256 megabytes input standar ...
- hihocoder 后缀自动机五·重复旋律8 求循环同构串出现的次数
描述 小Hi平时的一大兴趣爱好就是演奏钢琴.我们知道一段音乐旋律可以被表示为一段数构成的数列. 小Hi发现旋律可以循环,每次把一段旋律里面最前面一个音换到最后面就成为了原旋律的“循环相似旋律”,还可以 ...
- mysql case when使用记录
两种实现方式 第一种,CASE后面跟字段,当等于WHEN后面的值时,输出指定的数据 SELECT CASE gc.cat_id THEN '台球' THEN '羽毛球' ELSE '其它' END A ...
- .net framework 2.0使用扩展方法
.net framework中使用扩展方法,由网摘上看到,是因为编译器将扩展方法带上了ExtensionAttribute特性 要在.net framework 2.0中使用的话,可以自定义一个特性: ...