热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

分享Android蓝牙4.0(ble)开发的解决方案

这篇文章主要为大家分享了Android蓝牙4.0(ble)开发的解决方案,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

最近,随着智能穿戴式设备、智能医疗以及智能家居的普及,蓝牙开发在移动开中显得非常的重要。由于公司需要,研究了一下,蓝牙4.0在Android中的应用。

以下是我的一些总结。

1.先介绍一下关于蓝牙4.0中的一些名词吧:

(1)、GATT(Gneric Attibute  Profile)

通过ble连接,读写属性类小数据Profile通用的规范。现在所有的ble应用Profile  都是基于GATT

(2)、ATT(Attribute Protocal)

GATT是基于ATT Potocal的ATT针对BLE设备专门做的具体就是传输过程中使用尽量少的数据,每个属性都有个唯一的UUID,属性chartcteristics and Service的形式传输。

(3)、Service是Characteristic的集合。

(4)、Characteristic 特征类型。

比如,有个蓝牙ble的血压计。他可能包括多个Servvice,每个Service有包括多个Characteristic

注意:蓝牙ble只能支持Android 4.3以上的系统 SDK>=18

2.以下是开发的步骤:

2.1首先获取BluetoothManager 

代码如下:
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); 

2.2获取BluetoothAdapter

代码如下:
BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter(); 

2.3创建BluetoothAdapter.LeScanCallback

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { 
 
 @Override 
 public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) { 
 
  runOnUiThread(new Runnable() { 
  @Override 
  public void run() { 
   try { 
   String struuid = NumberUtils.bytes2HexString(NumberUtils.reverseBytes(scanRecord)).replace("-", "").toLowerCase(); 
   if (device!=null && struuid.contains(DEVICE_UUID_PREFIX.toLowerCase())) { 
    mBluetoothDevices.add(device); 
   } 
   } catch (Exception e) { 
   e.printStackTrace(); 
   } 
  } 
  }); 
 } 
 }; 

2.4.开始搜索设备。

代码如下:
mBluetoothAdapter.startLeScan(mLeScanCallback); 

2.5.BluetoothDevice  描述了一个蓝牙设备 提供了getAddress()设备Mac地址,getName()设备的名称。
2.6开始连接设备

 /** 
 * Connects to the GATT server hosted on the Bluetooth LE device. 
 * 
 * @param address 
 *  The device address of the destination device. 
 * 
 * @return Return true if the connection is initiated successfully. The 
 *  connection result is reported asynchronously through the 
 *  {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} 
 *  callback. 
 */ 
 public boolean connect(final String address) { 
 if (mBluetoothAdapter == null || address == null) { 
  Log.w(TAG, "BluetoothAdapter not initialized or unspecified address."); 
  return false; 
 } 
 
 // Previously connected device. Try to reconnect. (先前连接的设备。 尝试重新连接) 
 if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress) && mBluetoothGatt != null) { 
  Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection."); 
  if (mBluetoothGatt.connect()) { 
  mCOnnectionState= STATE_CONNECTING; 
  return true; 
  } else { 
  return false; 
  } 
 } 
 
 final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); 
 if (device == null) { 
  Log.w(TAG, "Device not found. Unable to connect."); 
  return false; 
 } 
 // We want to directly connect to the device, so we are setting the 
 // autoConnect 
 // parameter to false. 
 mBluetoothGatt = device.connectGatt(this, false, mGattCallback); 
 Log.d(TAG, "Trying to create a new connection."); 
 mBluetoothDeviceAddress = address; 
 mCOnnectionState= STATE_CONNECTING; 
 return true; 
 } 

2.7连接到设备之后获取设备的服务(Service)和服务对应的Characteristic。

// Demonstrates how to iterate through the supported GATT 
// Services/Characteristics. 
// In this sample, we populate the data structure that is bound to the 
// ExpandableListView 
// on the UI. 
private void displayGattServices(List gattServices) { 
 if (gattServices == null) 
 return; 
 String uuid = null; 
 ArrayList> gattServiceData = new ArrayList<>(); 
 ArrayList>> gattCharacteristicData = new ArrayList<>(); 
 
 mGattCharacteristics = new ArrayList<>(); 
 
 // Loops through available GATT Services. 
 for (BluetoothGattService gattService : gattServices) { 
 HashMap currentServiceData = new HashMap<>(); 
 uuid = gattService.getUuid().toString(); 
 if (uuid.contains("ba11f08c-5f14-0b0d-1080")) {//服务的uuid 
  //System.out.println("this gattService UUID is:" + gattService.getUuid().toString()); 
  currentServiceData.put(LIST_NAME, "Service_OX100"); 
  currentServiceData.put(LIST_UUID, uuid); 
  gattServiceData.add(currentServiceData); 
  ArrayList> gattCharacteristicGroupData = new ArrayList<>(); 
  List gattCharacteristics = gattService.getCharacteristics(); 
  ArrayList charas = new ArrayList<>(); 
 
  // Loops through available Characteristics. 
  for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { 
  charas.add(gattCharacteristic); 
  HashMap currentCharaData = new HashMap<>(); 
  uuid = gattCharacteristic.getUuid().toString(); 
  if (uuid.toLowerCase().contains("cd01")) { 
   currentCharaData.put(LIST_NAME, "cd01"); 
  } else if (uuid.toLowerCase().contains("cd02")) { 
   currentCharaData.put(LIST_NAME, "cd02"); 
  } else if (uuid.toLowerCase().contains("cd03")) { 
   currentCharaData.put(LIST_NAME, "cd03"); 
  } else if (uuid.toLowerCase().contains("cd04")) { 
   currentCharaData.put(LIST_NAME, "cd04"); 
  } else { 
   currentCharaData.put(LIST_NAME, "write"); 
  } 
 
  currentCharaData.put(LIST_UUID, uuid); 
  gattCharacteristicGroupData.add(currentCharaData); 
  } 
 
  mGattCharacteristics.add(charas); 
 
  gattCharacteristicData.add(gattCharacteristicGroupData); 
 
  mCharacteristicCD01 = gattService.getCharacteristic(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb")); 
  mCharacteristicCD02 = gattService.getCharacteristic(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb")); 
  mCharacteristicCD03 = gattService.getCharacteristic(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb")); 
  mCharacteristicCD04 = gattService.getCharacteristic(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb")); 
  mCharacteristicWrite = gattService.getCharacteristic(UUID.fromString("0000cd20-0000-1000-8000-00805f9b34fb")); 
 
  //System.out.println("=======================Set Notification=========================="); 
  // 开始顺序监听,第一个:CD01 
  mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD01, true); 
  mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD02, true); 
  mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD03, true); 
  mBluetoothLeService.setCharacteristicNotification(mCharacteristicCD04, true); 
 } 
 } 
} 

2.8获取到特征之后,找到服务中可以向下位机写指令的特征,向该特征写入指令。

public void wirteCharacteristic(BluetoothGattCharacteristic characteristic) { 
 
 if (mBluetoothAdapter == null || mBluetoothGatt == null) { 
  Log.w(TAG, "BluetoothAdapter not initialized"); 
  return; 
 } 
 
 mBluetoothGatt.writeCharacteristic(characteristic); 
 
 } 

2.9写入成功之后,开始读取设备返回来的数据。

private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { 
 @Override 
 public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { 
  String intentAction; 
  //System.out.println("=======status:" + status); 
  if (newState == BluetoothProfile.STATE_CONNECTED) { 
  intentAction = ACTION_GATT_CONNECTED; 
  mCOnnectionState= STATE_CONNECTED; 
  broadcastUpdate(intentAction); 
  Log.i(TAG, "Connected to GATT server."); 
  // Attempts to discover services after successful connection. 
  Log.i(TAG, "Attempting to start service discovery:" + mBluetoothGatt.discoverServices()); 
 
  } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { 
  intentAction = ACTION_GATT_DISCONNECTED; 
  mCOnnectionState= STATE_DISCONNECTED; 
  Log.i(TAG, "Disconnected from GATT server."); 
  broadcastUpdate(intentAction); 
  } 
 } 
 
 @Override 
 public void onServicesDiscovered(BluetoothGatt gatt, int status) { 
  if (status == BluetoothGatt.GATT_SUCCESS) { 
  broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED); 
  } else { 
  Log.w(TAG, "onServicesDiscovered received: " + status); 
  } 
 } 
 //从特征中读取数据 
 @Override 
 public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { 
  //System.out.println("onCharacteristicRead"); 
  if (status == BluetoothGatt.GATT_SUCCESS) { 
  broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); 
  } 
 } 
 //向特征中写入数据 
 @Override 
 public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { 
  //System.out.println("--------write success----- status:" + status); 
 } 
 
 /* 
  * when connected successfully will callback this method this method can 
  * dealwith send password or data analyze 
  
  *当连接成功将回调该方法 
  */ 
 @Override 
 public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { 
  broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); 
  if (characteristic.getValue() != null) { 
 
  //System.out.println(characteristic.getStringValue(0)); 
  } 
  //System.out.println("--------onCharacteristicChanged-----"); 
 } 
 
 @Override 
 public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { 
 
  //System.out.println("OnDescriptorWriteonDescriptorWrite= " + status + ", descriptor =" + descriptor.getUuid().toString()); 
 
  UUID uuid = descriptor.getCharacteristic().getUuid(); 
  if (uuid.equals(UUID.fromString("0000cd01-0000-1000-8000-00805f9b34fb"))) { 
  broadcastUpdate(ACTION_CD01NOTIDIED); 
  } else if (uuid.equals(UUID.fromString("0000cd02-0000-1000-8000-00805f9b34fb"))) { 
  broadcastUpdate(ACTION_CD02NOTIDIED); 
  } else if (uuid.equals(UUID.fromString("0000cd03-0000-1000-8000-00805f9b34fb"))) { 
  broadcastUpdate(ACTION_CD03NOTIDIED); 
  } else if (uuid.equals(UUID.fromString("0000cd04-0000-1000-8000-00805f9b34fb"))) { 
  broadcastUpdate(ACTION_CD04NOTIDIED); 
  } 
 } 
 
 @Override 
 public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) { 
  //System.out.println("rssi = " + rssi); 
 } 
 }; 
 
 ---------------------------------------------- 
 //从特征中读取数据 
 @Override 
 public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { 
  //System.out.println("onCharacteristicRead"); 
  if (status == BluetoothGatt.GATT_SUCCESS) { 
  broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic); 
  } 
 } 

2.10、断开连接

/** 
 * Disconnects an existing connection or cancel a pending connection. The 
 * disconnection result is reported asynchronously through the 
 * {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)} 
 * callback. 
 */ 
 public void disconnect() { 
 if (mBluetoothAdapter == null || mBluetoothGatt == null) { 
  Log.w(TAG, "BluetoothAdapter not initialized"); 
  return; 
 } 
 mBluetoothGatt.disconnect(); 
 } 

2.11、数据的转换方法

// byte转十六进制字符串 
 public static String bytes2HexString(byte[] bytes) { 
 String ret = ""; 
 for (byte aByte : bytes) { 
  String hex = Integer.toHexString(aByte & 0xFF); 
  if (hex.length() == 1) { 
  hex = '0' + hex; 
  } 
  ret += hex.toUpperCase(Locale.CHINA); 
 } 
 return ret; 
 } 
/** 
 * 将16进制的字符串转换为字节数组 
 * 
 * @param message 
 * @return 字节数组 
 */ 
 public static byte[] getHexBytes(String message) { 
 int len = message.length() / 2; 
 char[] chars = message.toCharArray(); 
 String[] hexStr = new String[len]; 
 byte[] bytes = new byte[len]; 
 for (int i = 0, j = 0; j 

大概整体就是如上的步骤,但是也是要具体根据厂家的协议来实现通信的过程。

就拿一个我们项目中的demo说一下。

一个蓝牙ble的血压计。 上位机---手机  下位机 -- 血压计

1.血压计与手机连接蓝牙之后。
2.上位机主动向下位机发送一个身份验证指令,下位机收到指令后开始给上位做应答,
3.应答成功,下位机会将测量的血压数据传送到上位机。
4.最后断开连接。

希望本文对大家学习Android蓝牙技术有所帮助。


推荐阅读
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • Android中高级面试必知必会,积累总结
    本文介绍了Android中高级面试的必知必会内容,并总结了相关经验。文章指出,如今的Android市场对开发人员的要求更高,需要更专业的人才。同时,文章还给出了针对Android岗位的职责和要求,并提供了简历突出的建议。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 【Windows】实现微信双开或多开的方法及步骤详解
    本文介绍了在Windows系统下实现微信双开或多开的方法,通过安装微信电脑版、复制微信程序启动路径、修改文本文件为bat文件等步骤,实现同时登录两个或多个微信的效果。相比于使用虚拟机的方法,本方法更简单易行,适用于任何电脑,并且不会消耗过多系统资源。详细步骤和原理解释请参考本文内容。 ... [详细]
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • 本文讲述了作者通过点火测试男友的性格和承受能力,以考验婚姻问题。作者故意不安慰男友并再次点火,观察他的反应。这个行为是善意的玩人,旨在了解男友的性格和避免婚姻问题。 ... [详细]
  • 安卓select模态框样式改变_微软Office风格的多端(Web、安卓、iOS)组件库——Fabric UI...
    介绍FabricUI是微软开源的一套Office风格的多端组件库,共有三套针对性的组件,分别适用于web、android以及iOS,Fab ... [详细]
  • 本文详细介绍了Linux中进程控制块PCBtask_struct结构体的结构和作用,包括进程状态、进程号、待处理信号、进程地址空间、调度标志、锁深度、基本时间片、调度策略以及内存管理信息等方面的内容。阅读本文可以更加深入地了解Linux进程管理的原理和机制。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 后台获取视图对应的字符串
    1.帮助类后台获取视图对应的字符串publicclassViewHelper{将View输出为字符串(注:不会执行对应的ac ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Google Play推出全新的应用内评价API,帮助开发者获取更多优质用户反馈。用户每天在Google Play上发表数百万条评论,这有助于开发者了解用户喜好和改进需求。开发者可以选择在适当的时间请求用户撰写评论,以获得全面而有用的反馈。全新应用内评价功能让用户无需返回应用详情页面即可发表评论,提升用户体验。 ... [详细]
author-avatar
美甲控Alily
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有