Bluetooth篇 开发实例之九 和蓝牙模块通信
首先,我们要去连接蓝牙模块,那么,我们只要写客户端的程序就好了,蓝牙模块就相当于服务端。
连接就需要UUID。
#蓝牙串口服务
SerialPortServiceClass_UUID = ‘{00001101-0000-1000-8000-00805F9B34FB}’
private UUID mUuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
第一步:
首先要连接设备。这个参考Android Developer的例子来写:Android Developer -- Bluetooth篇 开发实例之二 连接设备
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
代码:
/**
* 蓝牙客户端程序Socket,链接蓝牙服务器
*
* @author THINK
*
*/
private class BtClientThread extends Thread {
private BluetoothSocket btSocket; // 链接的Socket
private BluetoothAdapter btAdapter; // 蓝牙适配器,构造方法传入该值 /**
* 构造方法
*
* @param bluetoothAdapter
* @param btDevice
* @param uuid
*/
public BtClientThread(BluetoothAdapter btAdapter, BluetoothDevice btDevice, UUID uuid) {
BluetoothSocket tmp = null;
this.btAdapter = btAdapter;
try {
tmp = btDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
Log.d("h_bl", "BtClientThread不能获取到BluetoothSocket");
e.printStackTrace();
}
btSocket = tmp;
} /**
* 启动子线程去链接
*/
public void run() {
Log.d("h_bl", "BtClientThread进入线程");
// 链接时,蓝牙适配器要先取消搜索
btAdapter.cancelDiscovery();
try {
// 通过socket链接设备时,会阻塞线程,直到成功,或者抛出异常。
btSocket.connect();
} catch (IOException connectException) {
Log.d("h_bl", "BtClientThread通过socket链接设备失败");
// 不能链接设备时,就关闭socket的,并退出。
try {
btSocket.close();
} catch (IOException closeException) {
Log.d("h_bl", "BtClientThread不能正常关闭socket");
}
return;
}
// Do work to manage the connection (in a separate thread)
bConnectedThread = new BTConnectedThread(btSocket); // 当链接上蓝牙服务时
bConnectedThread.start();
Log.d("h_bl", "BtClientThread连接上设备了");
} /**
* 将取消正在进行的连接,并关闭套接字
*/
public void cancel() {
try {
btSocket.close();
} catch (IOException e) {
}
}
}
第二步:
管理连接。这个参考Android Developer的例子来写:Android Developer -- Bluetooth篇 开发实例之三 管理连接
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) { }
}
}
代码:
/**
* 蓝牙连接线程
*
* @author THINK
*
*/
private class BTConnectedThread extends Thread {
private BluetoothSocket mmSocket;
private InputStream mmInStream;
private OutputStream mmOutStream; public BTConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.d("h_bl", "socket.getInputStream()或者socket.getOutputStream()异常");
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
} public void run() {
Log.d("h_bl", "run()");
byte[] buffer = new byte[30]; // buffer store for the stream
int bytes; // bytes returned from read()
// 读程序要一直开启,死循环
while (true) {
Log.d("h_bl", "run()2");
try {
Log.d("h_bl", "run()3");
// Read from the InputStream
bytes = mmInStream.read(buffer);
Log.d("h_bl", "返回的数据的长度为" + bytes);
String readString = new String(buffer);
Log.d("h_bl", "返回的数据为" + readString);
//这边需要在处理
} 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);
//如果在用流的时候,没有用flush()这个方法,很多情况下会出现流的另一边读不到数据的问题,特别是在数据特别小的情况下
mmOutStream.flush();
} catch (IOException e) {
}
} /* Call this from the main Activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
以上,写不好,扩展性太差,有些,该判断的没有判断。
需要参考Bluetooth Chat sample app来写。
UUID参考地址:http://blog.csdn.net/wletv/article/details/8957612
Bluetooth篇 开发实例之九 和蓝牙模块通信的更多相关文章
- Android Developer -- Bluetooth篇 开发实例之四 API详解
http://www.open-open.com/lib/view/open1390879771695.html 这篇文章将会详细解析BluetoothAdapter的详细api, 包括隐藏方法, 每 ...
- Bluetooth篇 开发实例之八 匹配
自己写的App匹配蓝牙设备,不需要通过系统设置去连接. 匹配和通信是两回事. 用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK ...
- Android蓝牙实例(和单片机蓝牙模块通信)
最近做毕设,需要写一个简单的蓝牙APP进行交互,在网上也找了很多资料,终于给搞定了,这里分享一下^_^. 1.Android蓝牙编程 蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码 ...
- Bluetooth篇 开发实例之六 蓝牙RSSI计算距离
计算公式: d = 10^((abs(RSSI) - A) / (10 * n)) 其中: d - 计算所得距离 RSSI - 接收信号强度(负值) A - 发射端和接收端相隔1米时的信号强度 n - ...
- Bluetooth篇 开发实例之七 匹配&UUID
匹配和通信是两回事. 1.用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK中给出.但是可以通过反射来获取. 知道这两个API的 ...
- Bluetooth篇 开发实例之十 官网的Bluetooth Chat sample app.
运行的时候,会报错: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Action ...
- Android Developer -- Bluetooth篇 开发实例之三 管理连接
Managing a Connection When you have successfully connected two (or more) devices, each one will have ...
- Android Developer -- Bluetooth篇 开发实例之一 扫描设备
第一步:声明Bluetooth Permissions <!-- 设置蓝牙访问权限 --> <uses-permission android:name="android.p ...
- Bluetooth篇 开发实例之十一 官网的Bluetooth Chat sample的bug
当没有匹配的设备和没有找到可用设备的时候. // If there are paired devices, add each one to the ArrayAdapter if (pairedDev ...
随机推荐
- php中各种操作字符串和时间戳的代码关键词
<?php/** * Created by 郭鹏. * User: msi * Date: 2017/9/27 * Time: 14:17 */ //随机数生成器echo rand();echo ...
- DOM对象转化成jQuery对象
相比较jQuery转化成DOM,开发中更多的情况是把一个DOM对象加工成jQuery对象.$(参数)是一个多功能的方法,通过传递不同的参数而产生不同的作用. 如果传递给$(DOM)函数的参数是一个DO ...
- SQL视频总结
SQL是英文Structured Query Language的缩写,意思为结构化查询语言. SQL语言的主要功能就是同各种数据库建立联系,进行沟通.SQL被作为关系型数据库管理系统的标准语言. SQ ...
- [bzoj3813] 奇数国 [线段树+欧拉函数]
题面 传送门 思路 这题目是真的难读......阅读理解题啊...... 但是理解了以后就发现,题目等价于: 给你一个区间,支持单点修改,以及查询一段区间的乘积的欧拉函数值,这个答案对19961993 ...
- 洛谷 P3765 总统选举 解题报告
P3765 总统选举 题目背景 黑恶势力的反攻计划被小C成功摧毁,黑恶势力只好投降.秋之国的人民解放了,举国欢庆.此时,原秋之国总统因没能守护好国土,申请辞职,并请秋之国人民的大救星小C钦定下一任.作 ...
- idiots
idiots 题目描述 给定 $n$ 个长度分别为 $a_i$ 的木棒,问随机选择 $3$ 个木棒能够拼成三角形的概率. 输入格式 第一行一个正整数 nn. 第二行 nn 个正整数,第 ii 个数表示 ...
- Robocopy用法
----------------[参数]-------------------robocopy /?------------------------------------------------- ...
- 【CF1020D】The hat(交互,二分)
题意:有n个人围成一个圈,n为偶数,每个人有一个数字a[i],保证相邻两个人的数字差为1 最多可以询问60次,要求获得一个i使得a[i]=a[i+n/2] n<=1e5,abs(a[i])< ...
- PHP持久进程
在有些业务需求中,一个业务逻辑会涉及很多其他模块,这时可以把不需要返回的数据,扔到后台异步处理(比如注册时邮件验证,发邮件这个过程就可以扔到后台处理). 这个时候可以在后台起一个PHP进程,轮循处理业 ...
- knockout 表单绑定 要怎么Mapping才好
问题 之前有了解过knockout,学习过绑定语法,结合帮助文档,做个Demo倒也不成问题,但是部分地方很不爽,不知道是我的用法不对,还是功力不够. 比如说,标签里定义的data-bind属性名,必须 ...