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 ...
随机推荐
- FormsAuthentication类
理解代码: string cookieName = FormsAuthentication.FormsCookieName; FormsAuthentication类说明: // 摘要: // 为 W ...
- try...catch 语句
一般情况下,我们很少用到 try...catch 语句,但是有时候为了测试代码中的错误,也有可能会用到.小白我也在工作中用到过.那么好的程序设计,什么时候会用到呢? try...catch 一般用来捕 ...
- php + ajax实现 帖子点赞功能
知识: 一.首先页面需要加载jquery框架 二.ajax常用参数解释: ①.type:传输数据方式,get或者post ②.url:处理数据的PHP脚本 ③.data:传输的数据索引及值,值用js获 ...
- 新浪微博 page应用 自适应高度设定 终于找到解决方法
我做的是PAGE应用,无法自适应高度.找了好久解决方法. 用js 设置父窗口 iframe 也不好用,有的浏览器不兼容. 官方上说发是这样的: 应用动态高度自适应 Iframe高度:开发者可以使Ifr ...
- java链接数据库--Mysql
/************************************************************************* > File Name: Mysql.jav ...
- BZOJ1951 [Sdoi2010]古代猪文 【费马小定理 + Lucas定理 + 中国剩余定理 + 逆元递推 + 扩展欧几里得】
题目 "在那山的那边海的那边有一群小肥猪.他们活泼又聪明,他们调皮又灵敏.他们自由自在生活在那绿色的大草坪,他们善良勇敢相互都关心--" --选自猪王国民歌 很久很久以前,在山的那 ...
- 享元模式(FlyWeight Pattern)及其在java自动拆箱、自动装箱中的运用
本文主要从三个方面着手,第一:简要介绍享元模式.第二:享元模式在基本类型封装类中的运用以Integer为例进行阐述.第三:根据第一.第二的介绍,进而推出java是如何实现自动拆箱与装箱的. 第一:简要 ...
- MAC使用IDA PRO远程调试LINUX程序
1 背景 在学习Linux系统上的一些漏洞知识的时候,往往需要进行“实地测试”,但是在Linux系统上进行调试并不太方便,因为LINUX自带的GDB调试工具真的不太人性化,即使有GDBTUI之类的“伪 ...
- J2SE总结(一)-------容器
最近大家都在讨论容器以及如何在项目中去实际的应用它,由于之前对容器没有什么概念,所以把J2SE里面讲的容器的一些基础知识看了一下,总结一下最基本的东西. 围绕整章最核心的就属下面这张图了吧. 一.概念 ...
- WCF技术剖析 Two
WCF终结点和寻址之--AddressHead信息匹配代码 Contracts契约 using System; using System.Collections.Generic; using Syst ...