本文转载自:http://blog.csdn.net/geekdonie/article/details/7487761

由于近期正在开发一个通过蓝牙进行数据传递的模块,在参考了有关资料,并详细阅读了Android的官方文档后,总结了Android中蓝牙模块的使用。

【更新】之前承诺的蓝牙通讯模块的源码已经放出,详情请点击一下链接

http://blog.csdn.net/gd920129/article/details/7552110

1. 使用蓝牙的响应权限

  1. <uses-permission android:name="android.permission.BLUETOOTH" />
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

2. 配置本机蓝牙模块

在这里首先要了解对蓝牙操作一个核心类BluetoothAdapter

  1. BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
  2. //直接打开系统的蓝牙设置面板
  3. Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  4. startActivityForResult(intent, 0x1);
  5. //直接打开蓝牙
  6. adapter.enable();
  7. //关闭蓝牙
  8. adapter.disable();
  9. //打开本机的蓝牙发现功能(默认打开120秒,可以将时间最多延长至300秒)
  10. Intent discoveryIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
  11. discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);//设置持续时间(最多300秒)

3.搜索蓝牙设备

使用BluetoothAdapter的startDiscovery()方法来搜索蓝牙设备

startDiscovery()方法是一个异步方法,调用后会立即返回。该方法会进行对其他蓝牙设备的搜索,该过程会持续12秒。该方法调用后,搜索过程实际上是在一个System Service中进行的,所以可以调用cancelDiscovery()方法来停止搜索(该方法可以在未执行discovery请求时调用)。

请求Discovery后,系统开始搜索蓝牙设备,在这个过程中,系统会发送以下三个广播:

ACTION_DISCOVERY_START:开始搜索

ACTION_DISCOVERY_FINISHED:搜索结束

ACTION_FOUND:找到设备,这个Intent中包含两个extra fields:EXTRA_DEVICE和EXTRA_CLASS,分别包含BluetooDevice和BluetoothClass。

我们可以自己注册相应的BroadcastReceiver来接收响应的广播,以便实现某些功能

  1. // 创建一个接收ACTION_FOUND广播的BroadcastReceiver
  2. private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
  3. public void onReceive(Context context, Intent intent) {
  4. String action = intent.getAction();
  5. // 发现设备
  6. if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  7. // 从Intent中获取设备对象
  8. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  9. // 将设备名称和地址放入array adapter,以便在ListView中显示
  10. mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
  11. }
  12. }
  13. };
  14. // 注册BroadcastReceiver
  15. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  16. registerReceiver(mReceiver, filter); // 不要忘了之后解除绑定

4. 蓝牙Socket通信

如果打算建议两个蓝牙设备之间的连接,则必须实现服务器端与客户端的机制。当两个设备在同一个RFCOMM channel下分别拥有一个连接的BluetoothSocket,这两个设备才可以说是建立了连接。

服务器设备与客户端设备获取BluetoothSocket的途径是不同的。服务器设备是通过accepted一个incoming connection来获取的,而客户端设备则是通过打开一个到服务器的RFCOMM channel来获取的。

服务器端的实现

通过调用BluetoothAdapter的listenUsingRfcommWithServiceRecord(String, UUID)方法来获取BluetoothServerSocket(UUID用于客户端与服务器端之间的配对)

调用BluetoothServerSocket的accept()方法监听连接请求,如果收到请求,则返回一个BluetoothSocket实例(此方法为block方法,应置于新线程中)

如果不想在accept其他的连接,则调用BluetoothServerSocket的close()方法释放资源(调用该方法后,之前获得的BluetoothSocket实例并没有close。但由于RFCOMM一个时刻只允许在一条channel中有一个连接,则一般在accept一个连接后,便close掉BluetoothServerSocket

  1. private class AcceptThread extends Thread {
  2. private final BluetoothServerSocket mmServerSocket;
  3. public AcceptThread() {
  4. // Use a temporary object that is later assigned to mmServerSocket,
  5. // because mmServerSocket is final
  6. BluetoothServerSocket tmp = null;
  7. try {
  8. // MY_UUID is the app's UUID string, also used by the client code
  9. tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
  10. } catch (IOException e) { }
  11. mmServerSocket = tmp;
  12. }
  13. public void run() {
  14. BluetoothSocket socket = null;
  15. // Keep listening until exception occurs or a socket is returned
  16. while (true) {
  17. try {
  18. socket = mmServerSocket.accept();
  19. } catch (IOException e) {
  20. break;
  21. }
  22. // If a connection was accepted
  23. if (socket != null) {
  24. // Do work to manage the connection (in a separate thread)
  25. manageConnectedSocket(socket);
  26. mmServerSocket.close();
  27. break;
  28. }
  29. }
  30. }
  31. /** Will cancel the listening socket, and cause the thread to finish */
  32. public void cancel() {
  33. try {
  34. mmServerSocket.close();
  35. } catch (IOException e) { }
  36. }
  37. }

客户端的实现

通过搜索得到服务器端的BluetoothService

调用BluetoothService的listenUsingRfcommWithServiceRecord(String, UUID)方法获取BluetoothSocket(该UUID应该同于服务器端的UUID)

调用BluetoothSocket的connect()方法(该方法为block方法),如果UUID同服务器端的UUID匹配,并且连接被服务器端accept,则connect()方法返回

注意:在调用connect()方法之前,应当确定当前没有搜索设备,否则连接会变得非常慢并且容易失败

  1. private class ConnectThread extends Thread {
  2. private final BluetoothSocket mmSocket;
  3. private final BluetoothDevice mmDevice;
  4. public ConnectThread(BluetoothDevice device) {
  5. // Use a temporary object that is later assigned to mmSocket,
  6. // because mmSocket is final
  7. BluetoothSocket tmp = null;
  8. mmDevice = device;
  9. // Get a BluetoothSocket to connect with the given BluetoothDevice
  10. try {
  11. // MY_UUID is the app's UUID string, also used by the server code
  12. tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
  13. } catch (IOException e) { }
  14. mmSocket = tmp;
  15. }
  16. public void run() {
  17. // Cancel discovery because it will slow down the connection
  18. mBluetoothAdapter.cancelDiscovery();
  19. try {
  20. // Connect the device through the socket. This will block
  21. // until it succeeds or throws an exception
  22. mmSocket.connect();
  23. } catch (IOException connectException) {
  24. // Unable to connect; close the socket and get out
  25. try {
  26. mmSocket.close();
  27. } catch (IOException closeException) { }
  28. return;
  29. }
  30. // Do work to manage the connection (in a separate thread)
  31. manageConnectedSocket(mmSocket);
  32. }
  33. /** Will cancel an in-progress connection, and close the socket */
  34. public void cancel() {
  35. try {
  36. mmSocket.close();
  37. } catch (IOException e) { }
  38. }
  39. }

连接管理(数据通信)

分别通过BluetoothSocket的getInputStream()和getOutputStream()方法获取InputStream和OutputStream

使用read(bytes[])和write(bytes[])方法分别进行读写操作

注意:read(bytes[])方法会一直block,知道从流中读取到信息,而write(bytes[])方法并不是经常的block(比如在另一设备没有及时read或者中间缓冲区已满的情况下,write方法会block)

  1. private class ConnectedThread extends Thread {
  2. private final BluetoothSocket mmSocket;
  3. private final InputStream mmInStream;
  4. private final OutputStream mmOutStream;
  5. public ConnectedThread(BluetoothSocket socket) {
  6. mmSocket = socket;
  7. InputStream tmpIn = null;
  8. OutputStream tmpOut = null;
  9. // Get the input and output streams, using temp objects because
  10. // member streams are final
  11. try {
  12. tmpIn = socket.getInputStream();
  13. tmpOut = socket.getOutputStream();
  14. } catch (IOException e) { }
  15. mmInStream = tmpIn;
  16. mmOutStream = tmpOut;
  17. }
  18. public void run() {
  19. byte[] buffer = new byte[1024];  // buffer store for the stream
  20. int bytes; // bytes returned from read()
  21. // Keep listening to the InputStream until an exception occurs
  22. while (true) {
  23. try {
  24. // Read from the InputStream
  25. bytes = mmInStream.read(buffer);
  26. // Send the obtained bytes to the UI Activity
  27. mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
  28. .sendToTarget();
  29. } catch (IOException e) {
  30. break;
  31. }
  32. }
  33. }
  34. /* Call this from the main Activity to send data to the remote device */
  35. public void write(byte[] bytes) {
  36. try {
  37. mmOutStream.write(bytes);
  38. } catch (IOException e) { }
  39. }
  40. /* Call this from the main Activity to shutdown the connection */
  41. public void cancel() {
  42. try {
  43. mmSocket.close();
  44. } catch (IOException e) { }
  45. }
  46. }

引用资料:Android官方SDK、《Android/OPhone完全开发讲义》

Android蓝牙开发浅析【转】的更多相关文章

  1. Android 蓝牙开发(整理大全)

    Android蓝牙开发 鉴于国内Android蓝牙开发的例子很少,以及蓝牙开发也比较少用到,所以找的资料不是很全. (一): 由于Android蓝牙的通信都需要用到UUID,如果由手机发起搜索,当搜索 ...

  2. Android蓝牙开发

    Android蓝牙开发 近期做蓝牙小车,须要Android端来控制小车的运动.以此文记录开发过程. 使用HC-06无线蓝牙串口透传模块.对于其它的蓝牙设备本文相同适用. 蓝牙开发的流程: 获取本地蓝牙 ...

  3. Android蓝牙开发教程(三)——蓝牙设备相互通讯

    在上一篇中已经介绍如何连接我们搜索到的蓝牙设备,如果你还没阅读过,建议先看看上一篇文章Android蓝牙开发教程(二)——连接蓝牙设备 在上一篇文章中,无论是自动连接还是被动连接,连接成功后,都是将获 ...

  4. Android 蓝牙开发(3)——蓝牙的详细介绍

    前面的两篇文章,主要是在 Android 官网关于蓝牙介绍的基础上加上自己的理解完成的.主要针对的是 Android 开发中的一些 API 的使用. 第一篇文章 Android 蓝牙开发(1) 主要是 ...

  5. Qt on Android 蓝牙开发

    版权声明:本文为MULTIBEANS ORG研发跟随文章,未经MLT ORG允许不得转载. 最近做项目,需要开发安卓应用,实现串口的收发,目测CH340G在安卓手机上非常麻烦,而且驱动都是Java版本 ...

  6. 【转】android蓝牙开发---与蓝牙模块进行通信--不错

    原文网址:http://www.cnblogs.com/wenjiang/p/3200138.html 近半个月来一直在搞android蓝牙这方面,主要是项目需要与蓝牙模块进行通信.开头的进展很顺利, ...

  7. Android 蓝牙开发

    今天给大家带来蓝牙开发的基础,主要展示的是程序搜到蓝牙会通过list展示出来,并实时排序,远近与信号强弱 首先我们要有次jar包 watermark/2/text/aHR0cDovL2Jsb2cuY3 ...

  8. android蓝牙开发---与蓝牙模块进行通信

    近半个月来一直在搞android蓝牙这方面,主要是项目需要与蓝牙模块进行通信.开头的进展很顺利,但因为蓝牙模块不在我这里,所以只能用手机测试.一开头就发现手机的蓝牙不能用,为了证明这点,我刷了四次不同 ...

  9. Android 蓝牙开发之搜索、配对、连接、通信大全

            蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据 交换(使用2.4-2.485GHz的ISM波段的UHF无线电波).蓝牙设备最 ...

随机推荐

  1. 对ListView滚动状态的监听

    有的时候,我们需要对ListView滚动做一个相应的监听事件,例如:要实现如下图通讯录的功能: 思路为:首先呢,中间那个"路"字为一个TextView,它与ListView采用相对 ...

  2. win7上python+theano+keras安装

    https://blog.csdn.net/yongjiankuang/article/details/50485610 其实过程很简单,首先说一下安装条件: 1.win7 (32和64都可以,下载安 ...

  3. maven 工程聚合插件

    <!-- war包生成插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <a ...

  4. 常用PHP array数组函数

    array_rand  第二个参数用来确定要选出几个元素 如果选出的元素不止一个,则返回包含随机键名的数组,否则返回该元素的键名. $a=array("red","gre ...

  5. php 判断数组中是否有重复的值

    $input = array(4, "4", "3", 4, 3, "3"); $result = array_unique($input) ...

  6. 07 nginx Location之正则匹配

    一:Location之正则匹配 再来看,正则也来参与. location / { root   /usr/local/nginx/html; index  index.html index.htm; ...

  7. DFS应用——找出无向图的割点

    [0]README 0.1) 本文总结于 数据结构与算法分析, 源代码均为原创, 旨在 理解 "DFS应用于找割点" 的idea 并用源代码加以实现: 0.2) 必须要事先 做个s ...

  8. 基于HttpClient实现网络爬虫~以百度新闻为例

    转载请注明出处:http://blog.csdn.net/xiaojimanman/article/details/40891791 基于HttpClient4.5实现网络爬虫请訪问这里:http:/ ...

  9. PHP插入法排序

    /** 插入排序(Insertion Sort)的算法描述是一种简单直观的排序算法. 它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描, 找到相应位置并插入.插入排序在实现上 ...

  10. 验证-- email类型输入框(电子邮件地址)--multiple

    如果需要一个用来填写电子邮件地址的输入框,可以使用email类型.这样浏览器可以帮我们验证格式是否正确,而不需要自己写验证规则.原文:HTML5新控件 - email类型输入框(电子邮件地址) 1,只 ...