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 ...
随机推荐
- J2EE的十三种技术——JNDI
背景: 上一篇博客中介绍了J2EE的十三种技术之一--JDBC,主要用于提供了统一访问多种数据库的方式.这篇文章我们继续介绍J2EE的技术--JNDI. JNDI: Java Naming and D ...
- group_load,weight_load,group_capacity, group_weight大致都是啥数值
[ 113.180820] sgs->group_load:2039,sum_nr_running:2,sum_weighted_load:2039,sgs->group_capacity ...
- Charts & canvas & RGBA
Charts & canvas RGBA color let stopFlag = 0; // show Charts const showCharts = (name = "&qu ...
- Scala 基础(7)—— 函数字面量和一等函数
1. 函数字面量 在 Scala 基础(3)—— 基础类型和基础操作 中提到了函数字面量,这里具体解释函数字面量的语法. 下面展示一个具体的函数字面量,它由三部分组成: (x: Int, y: Int ...
- 【距离GDKOI:44天&GDOI:107天】【BZOJ1040】[ZJOI2008] 骑士 (环套树DP)
其实已经准备退役了,但GDOI之前还是会继续学下去的!!当成兴趣在学,已经对竞赛失去信心了的样子,我还是回去跪跪文化课吧QAQ 第一道环套树DP...其实思想挺简单的,就把环拆开,分类处理.若拆成开的 ...
- SPOJ 1825 Free Tour | 终极之树分治
求树上最长路径使得经过的拥挤节点个数不超过K //欢迎访问这个博客!http://www.cnblogs.com/luyouqi233/p/8036828.html #include<cstdi ...
- The Cave
The Cave 题目描述 给定一棵有n个节点的树,相邻两点之间的距离为1. 请找到一个点x,使其满足所有m条限制,其中第i条限制为dist(x,a[i])+dist(x,b[i])<=d[i] ...
- HDU 5690 矩阵快速幂
All X Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submi ...
- Educational Codeforces Round 42 (Rated for Div. 2) A
A. Equator time limit per test 2 seconds memory limit per test 256 megabytes input standard input ou ...
- Postfix+Sasl+Courier-authlib+Dovecot+MySQL+extmail 邮件系统部署
# yum remove postfix ##删除系统自带postfix# userdel postfix# groupdel postdrop# groupadd -g 2525 postfix# ...