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 ...
随机推荐
- PEAR DB 事务相关
1.autoCommit().commit().rollback() function autoCommit($onoff=false) 指定是否自动提交事务.有的后端数据库不支持. function ...
- 【bzoj1270】[BeijingWc2008]雷涛的小猫 dp
题目描述 输入 输出 样例输入 样例输出 8 题解 dp 设f[i][j]表示在第i棵树的j高度时最多吃到的柿子数. 那么只有两种可能能够到达这个位置:滑下来.跳下来. 滑下来直接用f[i][j+ ...
- java 图形化界面笔记(1)
目录 JFrame窗体......................................................................................... ...
- [CF1000E]We Need More Bosses
题目大意:给一张无向图,要求找一对$s$和$t$,使得其路径上的割边是最多的,输出其数量. 题解:把边双缩点以后求树的直径. 卡点:无 C++ Code: #include <cstdio> ...
- 洛谷 P1606 [USACO07FEB]荷叶塘Lilypad Pond 解题报告
P1606 [USACO07FEB]荷叶塘Lilypad Pond 题目描述 FJ has installed a beautiful pond for his cows' aesthetic enj ...
- 忽略node_modules目录
如上图所示添加node_modules目录到忽略文件列表里面,点击应用就可以了.
- Codeforces Round #359 (Div. 2) C
C. Robbers' watch time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...
- TCP面试题之四次挥手过程
TCP四次挥手过程: 1.第一次挥手:Client发送一个FIN,用来关闭Client到Server的数据传送,Client进入FIN_WAIT_1状态: 2.第二次挥手:Server收到FIN后,发 ...
- 百度AI开放平台 UNIT平台开发在线客服 借助百度的人工智能如何开发一个在线客服系统
这段时间在研究一些人工智能的产品,对比了国内几家做人工智能在线客服的,有些接口是要收费的,有些是免费的,但是做了很多限制,比如每天调用的接口次数限制是100次.后来就找到了百度的AI,大家也知道,目前 ...
- [bzoj4514][SDOI2016]数字配对——二分图
题目描述 传送门 题解: 这个题真的是巨坑,经过了6个WA,2个TLE,1个RE后才终于搞出来,中间都有点放弃希望了... 主要是一定要注意longlong! 下面开始说明题解. 朴素的想法是: 如果 ...