首先,我们要去连接蓝牙模块,那么,我们只要写客户端的程序就好了,蓝牙模块就相当于服务端。

连接就需要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篇 开发实例之九 和蓝牙模块通信的更多相关文章

  1. Android Developer -- Bluetooth篇 开发实例之四 API详解

    http://www.open-open.com/lib/view/open1390879771695.html 这篇文章将会详细解析BluetoothAdapter的详细api, 包括隐藏方法, 每 ...

  2. Bluetooth篇 开发实例之八 匹配

    自己写的App匹配蓝牙设备,不需要通过系统设置去连接. 匹配和通信是两回事. 用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK ...

  3. Android蓝牙实例(和单片机蓝牙模块通信)

    最近做毕设,需要写一个简单的蓝牙APP进行交互,在网上也找了很多资料,终于给搞定了,这里分享一下^_^. 1.Android蓝牙编程 蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码 ...

  4. Bluetooth篇 开发实例之六 蓝牙RSSI计算距离

    计算公式: d = 10^((abs(RSSI) - A) / (10 * n)) 其中: d - 计算所得距离 RSSI - 接收信号强度(负值) A - 发射端和接收端相隔1米时的信号强度 n - ...

  5. Bluetooth篇 开发实例之七 匹配&UUID

    匹配和通信是两回事. 1.用过Android系统设置(Setting)的人都知道蓝牙搜索之后可以建立配对和解除配对,但是这两项功能的函数没有在SDK中给出.但是可以通过反射来获取. 知道这两个API的 ...

  6. Bluetooth篇 开发实例之十 官网的Bluetooth Chat sample app.

    运行的时候,会报错: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Action ...

  7. Android Developer -- Bluetooth篇 开发实例之三 管理连接

    Managing a Connection When you have successfully connected two (or more) devices, each one will have ...

  8. Android Developer -- Bluetooth篇 开发实例之一 扫描设备

    第一步:声明Bluetooth Permissions <!-- 设置蓝牙访问权限 --> <uses-permission android:name="android.p ...

  9. Bluetooth篇 开发实例之十一 官网的Bluetooth Chat sample的bug

    当没有匹配的设备和没有找到可用设备的时候. // If there are paired devices, add each one to the ArrayAdapter if (pairedDev ...

随机推荐

  1. 1004 Counting Leaves (30 分)(树的遍历)

    给出一棵树,问每一层各有多少叶子节点 dfs遍历树 #include<bits/stdc++.h> using namespace std; vector<]; int n,m; i ...

  2. CentOS修改IP地址

    一.CentOS 修改IP地址修改对应网卡的IP地址的配置文件 # vi /etc/sysconfig/network-scripts/ifcfg-eth0   电信 # vi /etc/syscon ...

  3. FreeBSD NTP 简单使用

    FreeBSD NTP 简单使用 来源 https://blog.csdn.net/stevexk/article/details/1349506 1.ntptrace xxx.xxx.xxx.xxx ...

  4. [洛谷P4389]付公主的背包

    题目大意:有$n(n\leqslant10^5)$种物品,第$i$个物品体积为$v_i$,都有$10^5$件.给定$m(m\leqslant10^5)$,对于$s\in [1,m]$,请你回答用这些商 ...

  5. 自动设置 rem es模块写法

    export default function () { let html = document.documentElement; function onWindowResize() { if (ht ...

  6. NFS排错案例

    1.检验rpcinfo从客户端 # rpcinfo -p nfsserverip ,可以看到服务器端开的tcp/udp端口.默认都是打开的,客户端可以自己选择使用TCP/UDP program ver ...

  7. 远程桌面RDP不能粘贴文本

    刚才用远程桌面 登陆 服务器,突然发现不能在本机和远程服务器之间粘贴文本了,即不能从本机复制文本粘贴到服务器,也不能从服务器复制文本粘贴到本机. 在服务器上打开任务管理器,查看进程,有 rdpclip ...

  8. Python 二进制,十进制,十六进制转换

    十六进制 到 十进制 使用 int() 函数 ,第一个参数是字符串 '0Xff' ,第二个参数是说明,这个字符串是几进制的数.  转化的结果是一个十进制数. >>> int('0xf ...

  9. View的三次measure,两次layout和一次draw

    我在<Android视图结构>这篇文章中已经描述了Activity,Window和View在视图架构方面的关系.前天,我突然想到为什么在setContentView中能够调用findVie ...

  10. windwos grpc 编译

    此文档是windwos grpc c++ 编译 ,基于 vs2015 编译完成 获取gRPC源码 gRPC是开源框架,项目代码在github上,所以首先要安装github.github安装后,在指定文 ...